slogtest

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2024 License: BSD-3-Clause Imports: 5 Imported by: 0

Documentation

Overview

Package slogtest provides support for recording structured log slog messages during tests and verifying that the expected messages have been emitted.

`slogtest.Recorder` is a full-featured `slog.Handler` that records every structured log message and supports both shared attributes with `With()` and nested groups with `WithGroup()`.

`slogtest.GetAllAttrs` and `slogtest.GetFlattenAttrs` are helper functions to retrieve all the attributes of a record as a map, with fully resolved values.

`slogtest.WithSlogRecorder()` evaluate a function with a temporary `slogtest.Recorder` installed as the default logger of the slog packages.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetAllAttrs

func GetAllAttrs(r slog.Record) map[string]any

GetAllAttrs returns all the attributes of a record as a map, preserving the hierarchy of groups, with fully resolved values.

func GetFlattenAttrs

func GetFlattenAttrs(r slog.Record) map[string]any

GetFlattenAttrs returns all the attributes of a record as a single-level map, where keys of nested groups are expanded to a dot-separated syntax, and all the values are fully resolved.

func WithSlogRecorder

func WithSlogRecorder(f func(logs *Recorder))

WithSlogRecorder creates and install a new log recorder as the global slog.Default(), and passes the recorder to the nested function. Upon return, it restores the prior slog.Default() and attempts to restore the state of the log package as well -- if a log.SetOutput() was installed after a call to slog.SetDefault(), the output will not be restored. Note that this function has global side-effects and may not behave as expected with concurrently executing tests.

Types

type Recorder

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

Recorder is an implementation of slog.Handler that records each log entry for later verification during unit tests.

func (*Recorder) Enabled

func (h *Recorder) Enabled(context.Context, slog.Level) bool

func (*Recorder) GetRecords

func (h *Recorder) GetRecords() []slog.Record

func (*Recorder) Handle

func (h *Recorder) Handle(ctx context.Context, r slog.Record) error

func (*Recorder) WithAttrs

func (h *Recorder) WithAttrs(attrs []slog.Attr) slog.Handler

func (*Recorder) WithGroup

func (h *Recorder) WithGroup(name string) slog.Handler

Jump to

Keyboard shortcuts

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