logger

package module
v0.0.0-...-56af901 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2023 License: Apache-2.0 Imports: 5 Imported by: 0

README

logger

Simple library used for logging

Configuration

The Viper library is used for configuration management.

The configuration is stored inside memory structures, with hardcoded default values.

It can be adjusted during development using the configuration file, and at deploy time values can be overriden using environment variables.

The priority of assigned values for setting from lowest to highest priority is the following:

  • default values (lowest)
  • .env.file
  • enviromnet variable (highest)

Configuration options

Changing the default vaues should be avoided, but easily can be done directly manipulating the code.

File .env.yaml is preferd approach to adjust configuration during development. The file is bundled togehter with binary and is part of deployable package.

To override the value at deploy time use environment variables. Adjust the name of the variable to the full path to the setting in uppercase by replacing all dots with underscore.

The follwoing options can be configured:

log:
  format: string
  level: debug

Format can be either one of existing string and json, or new format can be implemented and used in configuration. Level can be one of the follwing "panic", "fatal", "error", "warn", "info", "debug" and "trace".

Example

Default setting assigned in memory structure for log.format value is string:

    // Default configurtion
    func (l *Config) Default() {
        l.Format = StringFormatter.Name
        l.Level = Error.Name
    }

The configuration in .env.yaml file for this setting can change it to another:

log:
  format: json
  level: debug

To change the level to warn of the application at deploy time, use the env variable:

LOG_LEVEL=warn

Usage Exаmple

Formatters for structured logging can be implemented and added easily. On global level the configuration defines the format and the minimal logging level for the whole application. Configutration is read and applied on global level when the InitLogger functionl is called. If not called, the default values are used.

    // -- Initialise configuration
    loggerConfig := new(logger.Config)
    err := loggerConfig.InitConfig()
    if err != nil {
        fmt.Printf("Cannot load the configuration: %s \n", err)
        os.Exit(1)
    }

    // -- Initialise logging system
    err = logger.InitLogger(loggerConfig)
    if err != nil {
        fmt.Printf("Cannot init the logging system: %s \n", err)
        os.Exit(1)
    }

Then use the logger for pringing the messages:

    // Create named logger
    mainLogger := logger.NewNamedLogger("main logger") 

    mainLogger.Panicf("%+v", appConfig)
    mainLogger.Panic("Panic entry")

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// StringFormatter instance
	StringFormatter = newFormatter("string", "%s [%s] %s [%s]: %v")

	// JSONFormatter instance
	JSONFormatter = newFormatter("json", "{\"time\":\"%s\",\"level\":\"%s\",\"trace_id\":\"%s\",\"logger\":\"%s\",\"msg\":\"%v\"}")
)
View Source
var (
	// Panic level
	Panic = newLevel(panicID, "panic")

	// Fatal level
	Fatal = newLevel(fatalID, "fatal")

	// Error level
	Error = newLevel(errorID, "error")

	// Warn level
	Warn = newLevel(warnID, "warn")

	// Info level
	Info = newLevel(infoID, "info")

	// Debug level
	Debug = newLevel(debugID, "debug")

	// Trace level
	Trace = newLevel(traceID, "trace")
)
View Source
var LogFormatter = StringFormatter

LogFormatter Global formatter for the application

View Source
var LogLevel = Error

LogLevel Global level for the application

Functions

func AllFormatters

func AllFormatters() map[string]Formatter

AllFormatters available formatters

func AllLevels

func AllLevels() map[string]Level

AllLevels logging levels

func GetViper

func GetViper() (*viper.Viper, error)

GetViper return the configured Viper instance

func InitLogger

func InitLogger(config Config) error

InitLogger initialise the global logger from configuration

Types

type Config

type Config struct {
	Format string `json:"log.format"`
	Level  string `json:"log.level"`
}

Config configuration fields

func (*Config) Default

func (l *Config) Default()

Default configurtion

func (*Config) InitConfig

func (l *Config) InitConfig() error

InitConfig the values from Config

func (*Config) LoadValues

func (l *Config) LoadValues(v *viper.Viper)

LoadValues from viper instance

func (*Config) Validate

func (l *Config) Validate() error

Validate validates the structure integrity

type Formatter

type Formatter struct {
	Name    string
	Pattern string
}

Formatter represents the logging Formatter

func (*Formatter) Parse

func (f *Formatter) Parse(timestamp time.Time, level Level, correlationID string, logerName string, v ...interface{}) string

Parse string

type Level

type Level struct {
	ID   int
	Name string
}

Level represents the logging level

type Logger

type Logger struct {
	// Name of the logger
	Name string

	// TraceID of the logger
	TraceID uuid.UUID
}

Logger usage

Initialise configuration

loggerConfig := new(logger.Config)
err := loggerConfig.InitConfig()

Global initialisation with configuration

logger.InitLogger(loggerConfig)

Create logger in place:

mainLogger := logger.NewNamedLogger("main logger")
mainLogger.GenTraceID()

To log a message with Fatal severity:

mainLogger.Fatal("Fatal entry")

Output depend on assigned formatter.

For string formatter it look like this:

2020-04-04T17:22:17+03:00 [fatal] e30375a6-4dc4-40be-8c5f-8656996298ce [main logger]: [[[Fatal entry]]]

For JSON formatter:

{"time":"2020-04-04T17:15:12+03:00","level":"fatal","corelation_id":"ace08634-1245-4557-9754-d015f8d0235a","logger":"main logger","msg":"[[[Fatal entry]]]"}

func NewAnnonymousLogger

func NewAnnonymousLogger() Logger

NewAnnonymousLogger creates new logger without name

func NewNamedLogger

func NewNamedLogger(name string) Logger

NewNamedLogger creates new named logger

func (*Logger) Debug

func (l *Logger) Debug(v ...interface{})

Debug ently logged

func (*Logger) Debugf

func (l *Logger) Debugf(format string, v ...interface{})

Debugf ently logged

func (*Logger) Error

func (l *Logger) Error(v ...interface{})

Error ently logged

func (*Logger) Errorf

func (l *Logger) Errorf(format string, v ...interface{})

Errorf ently logged

func (*Logger) Fatal

func (l *Logger) Fatal(v ...interface{})

Fatal ently logged

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, v ...interface{})

Fatalf ently logged

func (*Logger) GenTraceID

func (l *Logger) GenTraceID()

GenTraceID is used to generate and set new Correlation ID

func (*Logger) Info

func (l *Logger) Info(v ...interface{})

Info ently logged

func (*Logger) Infof

func (l *Logger) Infof(format string, v ...interface{})

Infof ently logged

func (*Logger) Panic

func (l *Logger) Panic(v ...interface{})

Panic ently logged

func (*Logger) Panicf

func (l *Logger) Panicf(format string, v ...interface{})

Panicf ently logged

func (*Logger) SetName

func (l *Logger) SetName(newName string)

SetName is used to set Name

func (*Logger) SetTraceID

func (l *Logger) SetTraceID(traceID uuid.UUID)

SetTraceID is used to set Correlation ID

func (*Logger) Trace

func (l *Logger) Trace(v ...interface{})

Trace ently logged

func (*Logger) Tracef

func (l *Logger) Tracef(format string, v ...interface{})

Tracef ently logged

func (*Logger) Warn

func (l *Logger) Warn(v ...interface{})

Warn ently logged

func (*Logger) Warnf

func (l *Logger) Warnf(format string, v ...interface{})

Warnf ently logged

Jump to

Keyboard shortcuts

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