native

package module
v1.5.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 5, 2024 License: MIT Imports: 11 Imported by: 11

README

PkgGoDev

slf4g Native

This is the native/reference implementation of Simple Log Framework for Golang (slf4g).

Usage

  1. Import the required dependencies to your current project (in best with a Go Modules project)

    $ go get -u github.com/echocat/slf4g
    $ go get -u github.com/echocat/slf4g/native
    
  2. Configure your application to use the selected logger implementation:

    This should be only done in main/main.go:

    package main
    
    import (
    	_ "github.com/echocat/slf4g/native"
    )
    
    func main() {
    	// do your stuff...
    }
    
  3. In each package create a logger variable, in best case you create a file named common.go or package.go which will contain it:

    package foo
    
    import (
    	"github.com/echocat/slf4g"
    )
    
    var logger = log.GetLoggerForCurrentPackage()
    
  4. Now you're ready to go. In every file of this package you can do stuff, like:

    package foo
    
    func MyFunction() {
    	logger.Info("Hello, world!")
    
    	if !loaded {
    		logger.With("field", 123).
    		       Warn("That's not great.")
    	}
    
    	if err := doSomething(); err != nil {
    		logger.WithError(err).
    		       Error("Doh!")
    	}
    }
    

    For sure, you're able to simply do stuff like that (although to ensure interoperability this is not recommended):

    package foo
    
    import (
    	"github.com/echocat/slf4g"
    )
    
    func MyFunction() {
    	log.Info("Hello, world!")
    
    	if !loaded {
    		log.With("field", 123).
    		    Warn("That's not great.")
    	}
    
    	if err := doSomething(); err != nil {
    		log.WithError(err).
    		    Error("Doh!")
    	}
    }
    

Customization

Set the log level globally to Debug

native.DefaultProvider.Level = level.Debug

Configure the text formatter to be used.

formatter.Default = formatter.NewText(func (v *formatter.Text) {
	// ... which never colorizes something.
	v.ColorMode = color.ModeNever

	// ... and just prints hours, minutes and seconds
	v.TimeLayout = "150405"
})

Configures a writer consumer that writes everything to stdout (instead of stderr; which is the default)

consumer.Default = consumer.NewWriter(os.Stdout)

Add an interceptor which will exit the application if someone logs something on level.Fatal or above. This is disabled by default.

interceptor.Default.Add(interceptor.NewFatal())

Change the location.Discovery to log everything detail instead of simplified (which is the default).

location.DefaultDiscovery = location.NewCallerDiscovery(func (t *location.CallerDiscovery) {
	t.ReportingDetail = location.CallerReportingDetailDetailed
})

Flags or similar

You can use the package facade/value to easily configure the logger using flag libraries like the SDK implementation or other compatible ones.

pv := value.NewProvider(native.DefaultProvider)

flag.Var(pv.Consumer.Formatter, "log.format", "Configures the log format.")
flag.Var(pv.Level, "log.level", "Configures the log level.")

flag.Parse()

Now you can call you program with:

$ <myExecutable> -log.format=json -log.level=debug ...

API

How the whole API works in general please refer the documentation of slf4g directly.

Documentation

Overview

This is the reference implementation of a logger of the slf4g framework (https://github.com/echocat/slf4g).

Usage

For the most common cases it is fully enough to anonymously import this package in your main.go; nothing more is needed.

github.com/foo/bar/main/main.go:

package main

import (
   "github.com/foo/bar"
   _ "github.com/echocat/slf4g/native"
)

func main() {
    bar.SayHello()
}

github.com/foo/bar/bar.go:

package bar

import (
   "github.com/echocat/slf4g"
)

func SayHello() {
    log.Info("Hello, world!")
}

See more useful stuff in the examples sections.

Example (Customization)
package main

import (
	"os"

	"github.com/echocat/slf4g/native/location"

	"github.com/echocat/slf4g/level"
	"github.com/echocat/slf4g/native"
	"github.com/echocat/slf4g/native/color"
	"github.com/echocat/slf4g/native/consumer"
	"github.com/echocat/slf4g/native/formatter"
	"github.com/echocat/slf4g/native/interceptor"
)

func main() {
	// Set the log level globally to Debug
	native.DefaultProvider.Level = level.Debug

	// Configure the text formatter to be used.
	formatter.Default = formatter.NewText(func(v *formatter.Text) {
		// ... which never colorizes something.
		v.ColorMode = color.ModeNever

		// ... and just prints hours, minutes and seconds
		v.TimeLayout = "150405"
	})

	// Configures a writer consumer that writes everything to stdout (instead
	// of stderr; which is the default)
	consumer.Default = consumer.NewWriter(os.Stdout)

	// Add an interceptor which will exit the application if someone logs
	// something on level.Fatal or above. This is disabled by default.
	interceptor.Default.Add(interceptor.NewFatal())

	// Change the location.Discovery to log everything detail instead of
	// simplified (which is the default).
	location.DefaultDiscovery = location.NewCallerDiscovery(func(t *location.CallerDiscovery) {
		t.ReportingDetail = location.CallerReportingDetailDetailed
	})
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultFieldKeysSpec = &FieldKeysSpecImpl{}

DefaultFieldKeysSpec is the default instance of FieldKeysSpec which should cover the majority of cases.

View Source
var DefaultProvider = &Provider{}

Functions

This section is empty.

Types

type CoreLogger

type CoreLogger struct {
	Level             level.Level
	Consumer          consumer.Consumer
	LocationDiscovery location.Discovery
	// contains filtered or unexported fields
}

CoreLogger implements log.CoreLogger of the slf4g framework for the "native" implementation.

You cannot create a working instance of this by yourself. It can only be done by the Provider instance. If you want to customize it you can use Provider.CoreLoggerCustomizer to done this.

func (*CoreLogger) Accepts added in v0.10.0

func (instance *CoreLogger) Accepts(e log.Event) bool

Accepts implements log.CoreLogger#Accepts()

func (*CoreLogger) GetLevel

func (instance *CoreLogger) GetLevel() level.Level

GetLevel returns the current level.Level where this log.CoreLogger is set to.

func (*CoreLogger) GetName

func (instance *CoreLogger) GetName() string

GetName implements log.CoreLogger#GetName()

func (*CoreLogger) GetProvider

func (instance *CoreLogger) GetProvider() log.Provider

GetProvider implements log.CoreLogger#GetProvider()

func (*CoreLogger) IsLevelEnabled

func (instance *CoreLogger) IsLevelEnabled(level level.Level) bool

IsLevelEnabled implements log.CoreLogger#IsLevelEnabled()

func (*CoreLogger) Log added in v0.3.0

func (instance *CoreLogger) Log(event log.Event, skipFrames uint16)

Log implements log.CoreLogger#Log()

func (*CoreLogger) NewEvent added in v0.10.0

func (instance *CoreLogger) NewEvent(l level.Level, values map[string]interface{}) log.Event

NewEvent implements log.CoreLogger#NewEvent()

func (*CoreLogger) NewEventWithFields added in v0.10.0

func (instance *CoreLogger) NewEventWithFields(l level.Level, f fields.ForEachEnabled) log.Event

NewEventWithFields provides a shortcut if an event should directly created from fields.

func (*CoreLogger) SetLevel

func (instance *CoreLogger) SetLevel(level level.Level)

SetLevel changes the current level.Level of this log.CoreLogger. If set to 0 it use the value of Provider.GetLevel().

type CoreLoggerCustomizer added in v0.9.0

type CoreLoggerCustomizer func(*Provider, *CoreLogger) log.CoreLogger

CoreLoggerCustomizer can be used by the Provider to customize created instances of CoreLogger. See Provider.CoreLoggerCustomizer

type FieldKeysSpec added in v0.9.0

type FieldKeysSpec interface {
	fields.KeysSpec

	// GetLocation defines the key location information of logged event are
	// stored inside. Such as the calling method, ...
	GetLocation() string
}

FieldKeysSpec defines the field keys supported this implementation of slf4g.

It is an extension of the default fields.KeysSpec.

func NewFieldKeysSpecFacade added in v0.9.0

func NewFieldKeysSpecFacade(provider func() FieldKeysSpec) FieldKeysSpec

NewFieldKeysSpecFacade creates a facade of FieldKeysSpec using the given provider.

type FieldKeysSpecImpl added in v0.9.0

type FieldKeysSpecImpl struct {
	fields.KeysSpecImpl

	// Location defines the used key of an location.
	// If empty "location" will be used instead.
	Location string
}

FieldKeysSpecImpl is a default implementation of FieldKeysSpec.

func (*FieldKeysSpecImpl) GetLocation added in v0.9.0

func (instance *FieldKeysSpecImpl) GetLocation() string

GetLocation implements FieldKeysSpec#GetLocation()

type Provider

type Provider struct {
	// Name represents the name of this Provider. If empty it will be "native"
	// by default.
	Name string

	// Level represents the level.Level of this Provider that is at least
	// required that the loggers managed by this Provider will respect logged
	// events. This can be overwritten by individual loggers. If this value is
	// not set it will be log.Info by default.
	Level level.Level

	// LevelNames is used to format the levels as human-readable
	// representations. If this is not set it will be level.DefaultNames by
	// default.
	LevelNames level.Names

	// LevelProvider is used to determine the log.Levels support by this
	// Provider and all of its managed loggers. If this is not set it will be
	// level.GetProvider() by default.
	LevelProvider level.Provider

	// Consumer is used to handle the logged events with. If this is not set it
	// will be consumer.Default by default.
	Consumer consumer.Consumer

	// LocationDiscovery is used to discover the location.Location where events
	// are happen. If this is not set it will be location.DefaultDiscovery by
	// default.
	LocationDiscovery location.Discovery

	// FieldKeysSpec defines what are the keys of the major fields managed by
	// this Provider and its managed loggers. If this is not set it will be
	// DefaultFieldKeysSpec by default.
	FieldKeysSpec FieldKeysSpec

	// CoreLoggerCustomizer will be called in every moment a logger instance
	// needs to be created (if configured).
	CoreLoggerCustomizer CoreLoggerCustomizer
	// contains filtered or unexported fields
}

Provider implements log.Provider of the slf4g framework for the "native" implementation.

Usually you should not be required to create by your self. Either use simply log.GetProvider() (which will return this provider once you imported this package at least one time somewhere) or if you want to customize its behavior simply modify DefaultProvider.

func (*Provider) GetAllLevels added in v0.4.0

func (instance *Provider) GetAllLevels() level.Levels

GetAllLevels implements log.Provider#GetAllLevels()

func (*Provider) GetConsumer

func (instance *Provider) GetConsumer() consumer.Consumer

GetConsumer returns the current consumer.Consumer where this log.Provider is set to.

func (*Provider) GetFieldKeysSpec added in v0.6.0

func (instance *Provider) GetFieldKeysSpec() fields.KeysSpec

GetFieldKeysSpec implements log.Provider#GetFieldKeysSpec()

func (*Provider) GetLevel

func (instance *Provider) GetLevel() level.Level

GetLevel returns the current level.Level where this log.Provider is set to.

func (*Provider) GetLevelNames added in v0.3.0

func (instance *Provider) GetLevelNames() level.Names

GetLevelNames returns an instance of level.Names that support by formatting level.Level managed by this Provider.

func (*Provider) GetLogger added in v0.4.0

func (instance *Provider) GetLogger(name string) log.Logger

GetLogger implements log.Provider#GetLogger()

func (*Provider) GetName added in v0.4.0

func (instance *Provider) GetName() string

GetName implements log.Provider#GetName()

func (*Provider) GetRootLogger added in v0.9.0

func (instance *Provider) GetRootLogger() log.Logger

GetRootLogger implements log.Provider#GetRootLogger()

func (*Provider) SetConsumer

func (instance *Provider) SetConsumer(v consumer.Consumer)

SetConsumer changes the current consumer.Consumer of this log.Provider. If set to nil consumer.Default will be used.

func (*Provider) SetLevel

func (instance *Provider) SetLevel(v level.Level)

SetLevel changes the current level.Level of this log.Provider. If set to 0 it will force this Provider to use log.Info.

Directories

Path Synopsis
Package color provides function to detect color support and also describe how the application should behave.
Package color provides function to detect color support and also describe how the application should behave.
Package consumer provides the functionally to print log events either to console, files, ...
Package consumer provides the functionally to print log events either to console, files, ...
facade
value
Package value provides a value facade for native.Provider to be able to easy be configured using flag libraries like the SDK implementation or other compatible ones.
Package value provides a value facade for native.Provider to be able to easy be configured using flag libraries like the SDK implementation or other compatible ones.
Formatter is used to format log events to a format which can logged to a console, file, ...
Formatter is used to format log events to a format which can logged to a console, file, ...
Hints are used while the processing of events and can adjust the behaviour how stuff is processed/handled.
Hints are used while the processing of events and can adjust the behaviour how stuff is processed/handled.
Interceptors are used to intercept instances of log.Event that are requested to be logged.
Interceptors are used to intercept instances of log.Event that are requested to be logged.
internal
Package native/level provides additions of slf4g/level for the native implementations.
Package native/level provides additions of slf4g/level for the native implementations.
Location defines where a log event happens.
Location defines where a log event happens.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL