logging

package module
v0.0.0-...-5f966df Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2024 License: Apache-2.0 Imports: 13 Imported by: 20

README

logging - A module providing convenience wrappers for log/slog

GoDoc Go Report Card

This module wraps the Go standard library logger log/slog (introduced in Go 1.21), providing a simplified interaction model and additional capabilities & convenience functions.

Features

  • Structured logging allowing for context-based cumulative field enrichment
  • Support for format-based output (such as Infof(...))
  • Support for various (extensible) output encodings (console, logfmt, JSON, ...)
  • Extension of standard logging levels by Fatal[f](...) and Panic[f](...) logging events (triggering the respective actions)
  • Performance-oriented approach to log level handling / filtering

Installation

go get -u github.com/els0r/telemetry/logging

Examples

Instantiate a new simple / plain console logger with INFO level, writing to STDOUT:

logger, err := logging.New(
    logging.LevelInfo,
    logging.EncodingPlain,
)
if err != nil {
	// Handle error, e.g. abort
}

Instantiate a new formatting logger with WARNING level, writing to STDOUT (ERROR level events and higher to STDERR) and adding the caller and a structured version log field to all emitted messages:

logger, err := logging.New(
	logging.LevelWarn,
	logging.EncodingLogfmt,
	logging.WithOutput(os.Stdout),
	logging.WithErrorOutput(os.Stderr),
	logging.WithVersion("v1.0.0"),
    logging.WithCaller(true),
)
if err != nil {
	// Handle error, e.g. abort
}

Enrich an existing context / logger in a function / method (labels set in parent context are present):

func handle(ctx context.Context, iface string) {
	ctx = logging.WithFields(ctx, slog.String("iface", iface))
	logger := logging.FromContext(ctx)

    logging.FromContext(ctx).Info("performing action") // will add [... iface=XYZ] and all labels from parent context

    // ...
}

Some simple log emission examples:

// INFO message, no formatting directive
logger.Info("this is a plain INFO message")

// DEBUG message, no formatting directive (will only show if log level is logging.LevelDebug)
logger.Debug("this is a plain DEBUG message")

// FATAL message (terminating the program) with formatting directive
err := errors.New("this is a critical error")
logger.Fatalf("critical error encountered: %s", err)

// PANIC message (throwing a stack trace / panic) with formatting directive
logger.Panicf("really critical error encountered: %s", err)

Documentation

Overview

Package logging supplies a global, structured logger

Index

Constants

View Source
const (
	LevelDebug = slog.LevelDebug
	LevelInfo  = slog.LevelInfo
	LevelWarn  = slog.LevelWarn
	LevelError = slog.LevelError
	LevelFatal = slog.Level(12)
	LevelPanic = slog.Level(13)

	// LevelUnknown specifies a level that the logger won't handle
	LevelUnknown = slog.Level(-255)
)

Names for common log levels

Variables

This section is empty.

Functions

func Init

func Init(level slog.Level, encoding Encoding, opts ...Option) error

Init initializes the global logger. The `encoding` variable sets whether content should be printed for console output or in JSON (for machine consumption)

func LevelFromString

func LevelFromString(lvl string) slog.Level

LevelFromString returns an slog.Level if the string matches one of the level's string descriptions. Otherwise the level LevelUnknown is returned (which won't be processed by the logger as a valid level)

func WithFields

func WithFields(ctx context.Context, fields ...slog.Attr) context.Context

WithFields returns a context that has extra fields added.

The method is meant to be used in conjunction with WithContext that selects the context-enriched logger.

The strength of this approach is that labels set in parent context are accessible

Types

type Encoding

type Encoding string

Encoding defines the type of log message encoding

const (
	// EncodingJSON encodes structured log messages as JSON
	// It uses the slog.JSONHandler under the hood
	EncodingJSON Encoding = "json"

	// EncodingLogfmt will output the messages in structured key=value pairs according
	// to the logfmt "standard"
	// It uses the slog.TextHandler under the hood
	EncodingLogfmt Encoding = "logfmt"

	// EncodingPlain causes only the message part of the log line to be printed
	// with the first letter of the message capitalized. It will not print any
	// other structured fields.
	//
	// The only thing setting it aside from fmt.Fprintln is that it respects the log level
	// it was initialized with
	EncodingPlain Encoding = "plain"
)

type L

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

L denotes a logger structure, wrapping a formatter

func FromContext

func FromContext(ctx context.Context) *L

FromContext returns a global logger which has as much context set as possible

func Logger

func Logger() *L

Logger returns a low allocation logger for performance critical sections

func New

func New(level slog.Level, encoding Encoding, opts ...Option) (*L, error)

New returns a new logger

func NewFromContext

func NewFromContext(ctx context.Context, level slog.Level, encoding Encoding, opts ...Option) (*L, error)

NewFromContext creates a new logger, deriving structured fields from the supplied context

func (L) Debug

func (f L) Debug(args ...interface{})

Debug will emit a log message with level debug

func (L) Debugf

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

Debugf allows writing of formatted debug messages to the logger

func (L) Error

func (f L) Error(args ...interface{})

Error will emit a log message with level error

func (L) Errorf

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

Errorf allows writing of formatted error messages to the logger. It's variadic arguments will _not_ add key-value pairs to the message, but be used as part of the msg's format string

func (L) Fatal

func (f L) Fatal(args ...interface{})

Fatal will emit a log message with level fatal and exit with a non-zero exit code

func (L) Fatalf

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

Fatalf will emit a formatted log message with level fatal and exit with a non-zero exit code

func (L) Info

func (f L) Info(args ...interface{})

Info will emit a log message with level info

func (L) Infof

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

Infof allows writing of formatted info messages to the logger

func (L) Panic

func (f L) Panic(args ...interface{})

Panic will emit a log message with level panic and panic

func (L) Panicf

func (f L) Panicf(format string, args ...interface{})

Panicf will emit a formatted log message with level panic and panic

func (L) Warn

func (f L) Warn(args ...interface{})

Warn will emit a log message with level warn

func (L) Warnf

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

Warnf allows writing of formatted warning messages to the logger

func (*L) With

func (l *L) With(args ...interface{}) *L

With runs With(args...) on the slog.Logger and attaches it

func (*L) WithGroup

func (l *L) WithGroup(group string) *L

WithGroup runs WithGroup(group) on the slog.Logger and attaches it

type Option

type Option func(*loggingConfig) error

Option denotes a functional option for the logging configuration

func WithCaller

func WithCaller(b bool) Option

WithCaller sets whether the calling source should be logged, since the operation is computationally expensive

func WithErrorOutput

func WithErrorOutput(w io.Writer) Option

WithErrorOutput sets the log output for level Error, Fatal and Panic. For the rest, the default output os.Stdout or the output set by `WithOutput` is chosen

func WithFileOutput

func WithFileOutput(path string) Option

WithFileOutput sets the log output to a file. The filepath can be one of the following:

- stdout: logs will be written to os.Stdout - stderr: logs will be written to os.Stderr - devnull: logs will be discarded - any other filepath: logs will be written to the file

The special filepaths are case insensitive, e.g. DEVNULL works just as well

func WithName

func WithName(name string) Option

WithName sets the application name as initial field present in all log messages

func WithOutput

func WithOutput(w io.Writer) Option

WithOutput sets the log output

func WithVersion

func WithVersion(version string) Option

WithVersion sets the application version as initial field present in all log messages

Jump to

Keyboard shortcuts

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