slog

package module
v0.0.0-...-b4d5967 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2025 License: MIT Imports: 12 Imported by: 76

README

slog

Structured logging.

slog is a library for capturing structured log information. In contrast to "traditional" logging libraries, slog:

  • captures a Context for each event
  • captures arbitrary key-value metadata on each log event

slog forwards messages to log by default. But you probably want to write a custom output to make use of the context and metadata. At Monzo, slog captures events both on a per-service and a per-request basis (using the context information) and sends them to a centralised logging system. This lets us view all the logs for a given request across all the micro-services it touches.

Usage

Internally at Monzo, we recommend that users always prefer structured logging where possible. An example of using slog for this would be:

slog.Info(ctx, "Loading widget", map[string]interface{}{
    "stage": "reticulating splines",
})
Errors

slog also provides a shorthand for capturing errors in the form of:

slog.Error(ctx, "Failed to load widget", err)

You may also add metadata to errors captured this way:

slog.Error(ctx, "Failed to load widget", err, map[string]interface{}{
    "user_id": 42,
})

Slog will pick up the first error it finds in the metadata and make it available in event.Error.

Other uses

For backwards-compatibility, slog accepts metadata in the form of map[string]string.

It also accepts format parameters in the style of Printf:

stage := "reticulating splines"
slog.Info(ctx, "Loading widget at stage: %s", stage)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Critical

func Critical(ctx context.Context, msg string, params ...interface{})

Critical constructs a logging event with critical severity. If the default Logger implements the LeveledLogger interface, we forward the requests via the Critical interface function. If not, the event is sent via the default Logger

func Debug

func Debug(ctx context.Context, msg string, params ...interface{})

Debug constructs a logging event with debug severity. If the default Logger implements the LeveledLogger interface, we forward the requests via the Debug interface function. If not, the event is sent via the default Logger

func Error

func Error(ctx context.Context, msg string, params ...interface{})

Error constructs a logging event with error severity. If the default Logger implements the LeveledLogger interface, we forward the requests via the Error interface function. If not, the event is sent via the default Logger

func FromError

func FromError(ctx context.Context, msg string, err error, params ...interface{})

FromError constructs a logging event with error severity by default. If the default Logger implements the FromErrorLogger interface, we forward the requests via the FromError interface function. In this case the severity will be inferred from the error.

func Info

func Info(ctx context.Context, msg string, params ...interface{})

Info constructs a logging event with info severity. If the default Logger implements the LeveledLogger interface, we forward the requests via the Info interface function. If not, the event is sent via the default Logger

func Log

func Log(evs ...Event)

Log sends the given Events via the default Logger

func Params

func Params(ctx context.Context) map[string]string

Params returns all parameters stored in the given context using WithParams. This function is intended to be used by libraries _other_ than slog that want access to the set of parameters (e.g. `monzo/terrors` functions).

The return value is guaranteed to be non-nil and can be safely mutated by the caller.

func SetDefaultLogger

func SetDefaultLogger(l Logger)

func Trace

func Trace(ctx context.Context, msg string, params ...interface{})

Trace constructs a logging event with trace severity. If the default Logger implements the LeveledLogger interface, we forward the requests via the Trace interface function. If not, the event is sent via the default Logger

func Warn

func Warn(ctx context.Context, msg string, params ...interface{})

Warn constructs a logging event with warn severity. If the DefaultLogger implements the LeveledLogger interface, we forward the requests via the Warn interface function. If not, the event is sent via the default Logger

func WithParam

func WithParam(ctx context.Context, key, value string) context.Context

WithParam is shorthand for calling WithParams with a single key-value pair.

func WithParams

func WithParams(parent context.Context, params map[string]string) context.Context

WithParams returns a copy of the parent context containing the given log parameters. Any log events generated using the returned context will include these parameters as metadata.

For example:

 ctx := slog.WithParams(ctx, map[string]string{
   "foo_id": fooID,
   "bar_id": barID,
 })

slog.Info(ctx, "Linking foo to bar")  // includes foo_id and bar_id parameters

If the parent context already contains parameters set by a previous call to WithParams, the new parameters will be merged with the existing set, with newer values taking precedence over older ones.

It is not safe to modify the supplied map after passing it to WithParams.

Types

type Event

type Event struct {
	Context         context.Context `json:"-"`
	Id              string          `json:"id"`
	Timestamp       time.Time       `json:"timestamp"`
	Severity        Severity        `json:"severity"`
	Message         string          `json:"message"`
	OriginalMessage string          `json:"-"`
	// Metadata are structured key-value pairs which describe the event.
	Metadata map[string]interface{} `json:"meta,omitempty"`
	// Labels, like Metadata, are key-value pairs which describe the event. Unlike Metadata, these are intended to be
	// indexed.
	Labels map[string]string `json:"labels,omitempty"`
	Error  interface{}       `json:"error,omitempty"`
}

An Event is a discrete logging event

func Eventf

func Eventf(sev Severity, ctx context.Context, msg string, params ...interface{}) Event

Eventf constructs an event from the given message string and formatting operands. Optionally, event metadata (map[string]interface{}, or map[string]string) can be provided as a final argument.

func (Event) String

func (e Event) String() string

type EventSet

type EventSet []Event

EventSet is a time-sortable collection of logging events.

func (EventSet) Len

func (es EventSet) Len() int

func (EventSet) Less

func (es EventSet) Less(i, j int) bool

func (EventSet) String

func (es EventSet) String() string

func (EventSet) Swap

func (es EventSet) Swap(i, j int)

type FromErrorLogger

type FromErrorLogger interface {
	FromError(ctx context.Context, msg string, err error, params ...interface{})
}

FromErrorLogger is a logger which logs errors. The severity of the log is inferred from the error.

type InMemoryLogger

type InMemoryLogger struct {
	*sync.Mutex
	// contains filtered or unexported fields
}

func NewInMemoryLogger

func NewInMemoryLogger() *InMemoryLogger

NewInMemoryLogger creates a logger that will keep all log events in memory Call InMemoryLogger.Events to access all logged events

func (*InMemoryLogger) Events

func (l *InMemoryLogger) Events() EventSet

func (*InMemoryLogger) Flush

func (l *InMemoryLogger) Flush() error

func (*InMemoryLogger) Log

func (l *InMemoryLogger) Log(evs ...Event)

type LeveledLogger

type LeveledLogger interface {
	Critical(ctx context.Context, msg string, params ...interface{})
	Error(ctx context.Context, msg string, params ...interface{})
	Warn(ctx context.Context, msg string, params ...interface{})
	Info(ctx context.Context, msg string, params ...interface{})
	Debug(ctx context.Context, msg string, params ...interface{})
	Trace(ctx context.Context, msg string, params ...interface{})
}

LeveledLogger is a logger which logs at different levels.

type Logger

type Logger interface {
	Log(evs ...Event)
	Flush() error
}

A Logger is a way of outputting events.

func DefaultLogger

func DefaultLogger() Logger

type MockLogger

type MockLogger struct {
	mock.Mock
}

func (*MockLogger) Critical

func (m *MockLogger) Critical(ctx context.Context, msg string, params ...interface{})

func (*MockLogger) Debug

func (m *MockLogger) Debug(ctx context.Context, msg string, params ...interface{})

func (*MockLogger) Error

func (m *MockLogger) Error(ctx context.Context, msg string, params ...interface{})

func (*MockLogger) Info

func (m *MockLogger) Info(ctx context.Context, msg string, params ...interface{})

func (*MockLogger) Trace

func (m *MockLogger) Trace(ctx context.Context, msg string, params ...interface{})

func (*MockLogger) Warn

func (m *MockLogger) Warn(ctx context.Context, msg string, params ...interface{})

type MultiLogger

type MultiLogger []Logger

A MultiLogger sends invocations to multiple Loggers.

func (MultiLogger) Flush

func (ls MultiLogger) Flush() error

Flush all sub-loggers.

func (MultiLogger) Log

func (ls MultiLogger) Log(evs ...Event)

Log the event to each sub-logger.

type Severity

type Severity int
const (
	ErrorMetadataKey          = "error"
	TimeFormat                = "2006-01-02 15:04:05-0700 (MST)"
	TraceSeverity    Severity = 1
	DebugSeverity    Severity = 2
	InfoSeverity     Severity = 3
	WarnSeverity     Severity = 4
	ErrorSeverity    Severity = 5
	CriticalSeverity Severity = 6
)

func (Severity) String

func (s Severity) String() string

type SeverityLogger

type SeverityLogger struct {
	Logger
}

SeverityLogger is a logger which can log at different severity levels.

func NewSeverityLogger

func NewSeverityLogger() SeverityLogger

NewSeverityLogger creates a SeverityLogger which wraps the default logger.

func (SeverityLogger) Critical

func (s SeverityLogger) Critical(ctx context.Context, msg string, params ...interface{})

Critical writes a Critical event to the logger.

func (SeverityLogger) Debug

func (s SeverityLogger) Debug(ctx context.Context, msg string, params ...interface{})

Debug writes a Debug event to the logger.

func (SeverityLogger) Error

func (s SeverityLogger) Error(ctx context.Context, msg string, params ...interface{})

Error writes a Error event to the logger.

func (SeverityLogger) Info

func (s SeverityLogger) Info(ctx context.Context, msg string, params ...interface{})

Info writes a Info event to the logger.

func (SeverityLogger) Trace

func (s SeverityLogger) Trace(ctx context.Context, msg string, params ...interface{})

Trace writes a Trace event to the logger.

func (SeverityLogger) Warn

func (s SeverityLogger) Warn(ctx context.Context, msg string, params ...interface{})

Warn writes a Warn event to the logger.

type StdlibLogger

type StdlibLogger struct{}

StdlibLogger is a very simple logger which forwards events to Go's standard library logger

func (StdlibLogger) Flush

func (s StdlibLogger) Flush() error

func (StdlibLogger) Log

func (s StdlibLogger) Log(evs ...Event)

Jump to

Keyboard shortcuts

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