slogtest

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2025 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package slogtest provides utilities for emitting test logs using clog.

func TestExample(t *testing.T) {
	ctx := slogtest.Context(t)
	clog.FromContext(ctx).With("foo", "bar").Info("hello world")
}

This produces the following test output:

=== RUN   TestExample
	slogtest.go:24: level=INFO source=/path/to/example_test.go:13 msg="hello world" foo=bar

This package is intended to be used in tests only.

In Go 1.24, *testing.T etc added `t.Context()` methods, which return a context.Context to be used in tests. You can use `clog.FromContext(t.Context())` to get a logger in tests instead, and configure the default logger to get the same logging behavior as `slogtest.Context(t)`.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Context added in v1.5.0

func Context(t Logger) context.Context

Context returns a context with a logger to be used in tests.

func RemoveTime

func RemoveTime(groups []string, a slog.Attr) slog.Attr

RemoveTime removes the top-level time attribute. It is intended to be used as a ReplaceAttr function, to make example output deterministic.

This is taken from slog/internal/slogtest.RemoveTime.

func TestContextWithLogger deprecated

func TestContextWithLogger(t Logger) context.Context

TestContextWithLogger returns a context with a logger to be used in tests

Deprecated: Use Context instead.

func TestLogger

func TestLogger(t Logger) *clog.Logger

TestLogger gets a logger to use in unit and end to end tests. This logger is configured to log at debug level.

func TestLoggerWithOptions added in v1.5.0

func TestLoggerWithOptions(t Logger, opts *slog.HandlerOptions) *clog.Logger

TestLoggerWithOptions gets a logger to use in unit and end to end tests.

Types

type Logger

type Logger interface {
	Log(args ...any)
	Context() context.Context
}

Jump to

Keyboard shortcuts

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