logger

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2024 License: MIT Imports: 9 Imported by: 6

README

go-logger

This Go package is used to offer a unified logging interface among projects.

Install

go get github.com/coopnorge/go-logger

Import

import "github.com/coopnorge/go-logger"

Default behavior

By default, all logs will include:

  • Log level
  • Full path to file which called the logger, and line number
  • Signature of the function that called the logger
  • Timestamp of the log entry

Example log entry with default settings:

package main

import "github.com/coopnorge/go-logger"

func main() {
	logger.Warn("something went wrong")
	// Output:
	// {"file":"/Users/anonymous/Projects/my-project/main.go:7","function":"main.main","level":"warning","msg":"something went wrong","time":"2022-02-17T15:04:06+01:00"}
}

Example usage

See logger_examples_test.go for more examples.

Using global logger
package main

import "github.com/coopnorge/go-logger"

func main() {
	logger.Info("this won't be logged because the default log level is higher than info")
	logger.Warn("but this will be logged")
	// Output:
	// {"level":"warning","msg":"but this will be logged","time":"2022-02-17T11:01:28+01:00"}
}
Setting log level
package main

import "github.com/coopnorge/go-logger"

func main() {
	// global logger
	logger.Info("this won't be logged because the default log level is higher than info")
	logger.ConfigureGlobalLogger(logger.WithLevel(logger.LevelInfo))
	logger.Info("now this will be logged")
	// Output:
	// {"level":"info","msg":"now this will be logged","time":"2022-02-17T10:54:54+01:00"}

	// logger instance
	prodLogger := logger.New(logger.WithLevel(logger.LevelWarn))
	prodLogger.Info("this won't be logged because prodLogger's level is set to Warn...")
	prodLogger.Error("...but this will, because Error >= Warn")
	// Output:
	// {"level":"error","msg":"...but this will, because Error \u003e= Warn","time":"2022-02-17T10:54:54+01:00"}

	debugLogger := logger.New(logger.WithLevel(logger.LevelDebug))
	debugLogger.Debug("this logger will log anything as Debug is the lowest available level")
	debugLogger.Warn("and this will be logged too")
	// Output:
	// {"level":"debug","msg":"this logger will log anything as Debug is the lowest available level","time":"2022-02-17T10:54:54+01:00"}
	// {"level":"warning","msg":"and this will be logged too","time":"2022-02-17T10:54:54+01:00"}
}

Adapters

Gorm

To ensure that Gorm outputs logs in the correct format Gorm must be configured with a custom logger.

package main

import (
	gormLogger "github.com/coopnorge/go-logger/adapter/gorm"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

func main() {
	l, err := gormLogger.NewLogger(gormLogger.WithGlobalLogger())
	if err != nil {
		panic(err)
	}
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
		Logger: l,
	})
	if err != nil {
		panic(err)
	}
}
Datadog

To ensure that Datadog outputs logs in the correct format Datadog must be configured with a custom logger.

package main

import (
	"github.com/coopnorge/go-logger/adapter/datadog"

	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
)

func main() {
	l, err := datadog.NewLogger(datadog.WithGlobalLogger())
	if err != nil {
		panic(err)
	}
	ddtrace.UseLogger(l)
}

Documentation

Index

Examples

Constants

View Source
const (
	// LevelFatal is to be used to log predictable errors that make the service unusable, eg misconfiguration. After logging, the app will be shut down.
	LevelFatal = iota
	// LevelError  isto be used for recoverable errors that limit the service's functionality, eg timeouts.
	LevelError
	// LevelWarn is to be used for non-critical errors that may require some attention.
	LevelWarn
	// LevelInfo is to be used for monitoring successful interactions, eg run time or job result.
	LevelInfo
	// LevelDebug should only be used in dev/test environments.
	LevelDebug
)

Variables

This section is empty.

Functions

func ConfigureGlobalLogger

func ConfigureGlobalLogger(opts ...LoggerOption)

ConfigureGlobalLogger applies supplied logger options to the global logger

func Debug

func Debug(args ...interface{})

Debug uses global logger to log payload on "debug" level

func Debugf

func Debugf(format string, args ...interface{})

Debugf uses global logger to log payload on "debug" level

func Error

func Error(args ...interface{})

Error uses global logger to log payload on "error" level

func Errorf

func Errorf(format string, args ...interface{})

Errorf uses global logger to log payload on "error" level

func Fatal

func Fatal(args ...interface{})

Fatal uses global logger to log payload on "fatal" level

func Fatalf

func Fatalf(format string, args ...interface{})

Fatalf uses global logger to log payload on "fatal" level

func Info

func Info(args ...interface{})

Info uses global logger to log payload on "info" level

Example
logger := New(WithNowFunc(mockNowFunc), WithReportCaller(false))
logger.Warn("foobar")
logger.Info("i won't be logged because the default log level is higher than info")
logger.Error("foobar")
Output:

{"level":"warning","msg":"foobar","time":"2020-10-10T10:10:10Z"}
{"level":"error","msg":"foobar","time":"2020-10-10T10:10:10Z"}

func Infof

func Infof(format string, args ...interface{})

Infof uses global logger to log payload on "info" level

func SetLevel

func SetLevel(level Level)

SetLevel sets minimum log level for global logger

func SetNowFunc

func SetNowFunc(nowFunc NowFunc)

SetNowFunc sets `now` func user by global logger

func SetOutput

func SetOutput(output io.Writer)

SetOutput changes global logger's output

func SetReportCaller

func SetReportCaller(enable bool)

SetReportCaller allows controlling if caller info should be attached to logs by global logger

func Warn

func Warn(args ...interface{})

Warn uses global logger to log payload on "warn" level

func Warnf

func Warnf(format string, args ...interface{})

Warnf uses global logger to log payload on "warn" level

Types

type Entry

type Entry struct {
	// contains filtered or unexported fields
}

Entry represents a logging entry and all supported method we use

func WithContext added in v0.6.0

func WithContext(ctx context.Context) *Entry

WithContext creates log entry using global logger

func WithError added in v0.4.0

func WithError(err error) *Entry

WithError is a convenience wrapper for WithField("err", err)

Example
logger := New(WithNowFunc(mockNowFunc), WithReportCaller(false))

err := errors.New("Test error")
logger.WithError(err).Error("Operation failed")
Output:

{"error":"Test error","level":"error","msg":"Operation failed","time":"2020-10-10T10:10:10Z"}

func WithField added in v0.3.0

func WithField(key string, value interface{}) *Entry

WithField creates log entry using global logger

func WithFields

func WithFields(fields Fields) *Entry

WithFields creates log entry using global logger

Example
// Example runner replaces os.Stdout to catch output and compares it with desired output.
// Global logger instance sets default output to os.Stdin before example runner has a chance to overwrite it.
// Within this function, os.Stdin is already replaced by example runner.
// So we need to tell the global logger instance to use modified os.Stdout as its output,
// otherwise example runner will fail as logs would be written to real stdout
// and nothing would get written to example runnner's buffer.
oldOutput := globalLogger.output
oldNowFunc := globalLogger.now
defer func() {
	ConfigureGlobalLogger(WithOutput(oldOutput), WithNowFunc(oldNowFunc), WithReportCaller(true))
}()
ConfigureGlobalLogger(WithOutput(os.Stdout), WithNowFunc(mockNowFunc), WithReportCaller(false))

WithFields(Fields{
	"timeSpentOnConfiguration": 0,
	"defaultsLoaded":           true,
}).Warn("use default logger with 0 configuration")
WithField("singleField", true).Warn("example with a single field")
Output:

{"defaultsLoaded":true,"level":"warning","msg":"use default logger with 0 configuration","time":"2020-10-10T10:10:10Z","timeSpentOnConfiguration":0}
{"level":"warning","msg":"example with a single field","singleField":true,"time":"2020-10-10T10:10:10Z"}

func (*Entry) Debug

func (e *Entry) Debug(args ...interface{})

Debug forwards a debugging logging call

func (*Entry) Debugf

func (e *Entry) Debugf(format string, args ...interface{})

Debugf forwards a debugging logging call

func (*Entry) Error

func (e *Entry) Error(args ...interface{})

Error forwards an error logging call

func (*Entry) Errorf

func (e *Entry) Errorf(format string, args ...interface{})

Errorf forwards an error logging call

func (*Entry) Fatal

func (e *Entry) Fatal(args ...interface{})

Fatal forwards a fatal logging call

func (*Entry) Fatalf

func (e *Entry) Fatalf(format string, args ...interface{})

Fatalf forwards a fatal logging call

func (*Entry) Info

func (e *Entry) Info(args ...interface{})

Info forwards a logging call in the (format, args) format

func (*Entry) Infof

func (e *Entry) Infof(format string, args ...interface{})

Infof forwards a logging call in the (format, args) format

func (*Entry) Warn

func (e *Entry) Warn(args ...interface{})

Warn forwards a warning logging call

func (*Entry) Warnf

func (e *Entry) Warnf(format string, args ...interface{})

Warnf forwards a warning logging call

func (*Entry) WithContext added in v0.7.0

func (e *Entry) WithContext(ctx context.Context) *Entry

WithContext sets the context for the log-message. Useful when using hooks.

func (*Entry) WithError added in v0.7.0

func (e *Entry) WithError(err error) *Entry

WithError is a convenience wrapper for WithField("error", err)

func (*Entry) WithField added in v0.7.0

func (e *Entry) WithField(key string, value interface{}) *Entry

WithField forwards a logging call with a field

func (*Entry) WithFields added in v0.7.0

func (e *Entry) WithFields(fields Fields) *Entry

WithFields forwards a logging call with fields

type Fields

type Fields map[string]interface{}

Fields type, used to pass to `WithFields`.

type Hook added in v0.6.0

type Hook interface {
	Fire(*HookEntry) (changed bool, err error)
}

Hook defines the interface a custom Hook needs to implement

type HookEntry added in v0.6.0

type HookEntry struct {
	// Contains all the fields set by the user.
	Data Fields

	// Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic
	// This field will be set on entry firing and the value will be equal to the one in Logger struct field.
	Level Level

	// Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic
	Message string

	// Contains the context set by the user. Useful for hook processing etc.
	Context context.Context
}

HookEntry contains the fields provided for mutation in a hook.

type HookFunc added in v0.6.0

type HookFunc func(*HookEntry) (changed bool, err error)

HookFunc can be used to convert a simple function to implement the Hook interface.

func (HookFunc) Fire added in v0.6.0

func (hf HookFunc) Fire(he *HookEntry) (changed bool, err error)

Fire redirects a function call to the function receiver

type Level

type Level uint8

Level is an integer representation of the logging level

func LevelNameToLevel added in v0.4.0

func LevelNameToLevel(name string) (l Level, ok bool)

LevelNameToLevel converts a named log level to the Level type

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger is our logger with the needed structured logger we use

func Global

func Global() *Logger

Global logger that can be accessed without prior instantiation

Example
oldOutput := globalLogger.output
oldNowFunc := globalLogger.now
defer func() {
	ConfigureGlobalLogger(WithOutput(oldOutput), WithNowFunc(oldNowFunc), WithReportCaller(true))
}()
ConfigureGlobalLogger(WithOutput(os.Stdout), WithNowFunc(mockNowFunc), WithReportCaller(false))

funcThatAcceptsInterface(Global())
Output:

{"level":"warning","msg":"foobar","time":"2020-10-10T10:10:10Z"}

func New

func New(opts ...LoggerOption) *Logger

New creates and returns a new logger with supplied options

func (*Logger) Debug

func (logger *Logger) Debug(args ...interface{})

Debug forwards a debugging logging call

func (*Logger) Debugf

func (logger *Logger) Debugf(format string, args ...interface{})

Debugf forwards a debugging logging call

func (*Logger) Error

func (logger *Logger) Error(args ...interface{})

Error forwards an error logging call

func (*Logger) Errorf

func (logger *Logger) Errorf(format string, args ...interface{})

Errorf forwards an error logging call

func (*Logger) Fatal

func (logger *Logger) Fatal(args ...interface{})

Fatal forwards a fatal logging call

func (*Logger) Fatalf

func (logger *Logger) Fatalf(format string, args ...interface{})

Fatalf forwards a fatal logging call

func (*Logger) Info

func (logger *Logger) Info(args ...interface{})

Info forwards a logging call in the (format, args) format

func (*Logger) Infof

func (logger *Logger) Infof(format string, args ...interface{})

Infof forwards a logging call in the (format, args) format

func (*Logger) OutputHandler added in v0.2.1

func (logger *Logger) OutputHandler() io.Writer

OutputHandler returns logger output handler

func (*Logger) Warn

func (logger *Logger) Warn(args ...interface{})

Warn forwards a warning logging call

func (*Logger) Warnf

func (logger *Logger) Warnf(format string, args ...interface{})

Warnf forwards a warning logging call

func (*Logger) WithContext added in v0.6.0

func (logger *Logger) WithContext(ctx context.Context) *Entry

WithContext forwards a logging call with fields

func (*Logger) WithError added in v0.4.0

func (logger *Logger) WithError(err error) *Entry

WithError is a convenience wrapper for WithField("error", err)

func (*Logger) WithField added in v0.3.0

func (logger *Logger) WithField(key string, value interface{}) *Entry

WithField forwards a logging call with a field

func (*Logger) WithFields

func (logger *Logger) WithFields(fields Fields) *Entry

WithFields forwards a logging call with fields

type LoggerOption

type LoggerOption interface {
	Apply(l *Logger)
}

LoggerOption defines an applicator interface

func WithHook added in v0.6.0

func WithHook(hook Hook) LoggerOption

WithHook allows for connecting a hook to the logger, which will be triggered on all log-entries.

func WithHookFunc added in v0.6.0

func WithHookFunc(hook HookFunc) LoggerOption

WithHookFunc allows for connecting a hook to the logger, which will be triggered on all log-entries.

func WithLevel

func WithLevel(level Level) LoggerOption

WithLevel sets minimum level for filtering logs

Example
logger := New(WithNowFunc(mockNowFunc), WithLevel(LevelInfo), WithReportCaller(false))
logger.Info("now log level is set to info or lower, I will be logged")
Output:

{"level":"info","msg":"now log level is set to info or lower, I will be logged","time":"2020-10-10T10:10:10Z"}

func WithLevelName added in v0.4.0

func WithLevelName(level string) LoggerOption

WithLevelName sets minimum level for filtering logs by name

Example
logger := New(WithNowFunc(mockNowFunc), WithLevelName("info"), WithReportCaller(false))
logger.Info("now log level is set to info or lower, I will be logged")
Output:

{"level":"info","msg":"now log level is set to info or lower, I will be logged","time":"2020-10-10T10:10:10Z"}

func WithNowFunc

func WithNowFunc(nowFunc NowFunc) LoggerOption

WithNowFunc overrides default function used to determine current time. Intended to be used in tests only.

func WithOutput

func WithOutput(output io.Writer) LoggerOption

WithOutput overrides default output the logs are written to.

func WithReportCaller

func WithReportCaller(enable bool) LoggerOption

WithReportCaller allows enabling/disabling including calling method in the log entry

type LoggerOptionFunc

type LoggerOptionFunc func(l *Logger) //nolint:all

LoggerOptionFunc defines a function which modifies a logger

func (LoggerOptionFunc) Apply

func (lof LoggerOptionFunc) Apply(l *Logger)

Apply redirects a function call to the function receiver

type NowFunc

type NowFunc func() time.Time

NowFunc is a typedef for a function which returns the current time

Directories

Path Synopsis
adapter

Jump to

Keyboard shortcuts

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