slogctx

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2023 License: Apache-2.0 Imports: 5 Imported by: 0

README

slogctx

Go Reference

Context aware slog

Usage

Context Logger

The context Logger can be used to use Loggers from the context. This is sometimes preferred over the Context Handler, since this can make it easier to use different loggers in different contexts (e.g. testing).

This approach is heavily inspired by knative.dev/pkg/logging

func main() {
	log := slogctx.New(slog.Default).With("a", "b")
	ctx := slogctx.WithLogger(log)

	// Grab logger from context and use
	slogctx.FromContext(ctx).With("foo", "bar").Infof("hello world")

	// Package level context loggers are also aware
	slogctx.ErrorContext(ctx, "asdf")
}
2023/12/12 18:27:27 INFO hello world a=b foo=bar
2023/12/12 18:27:27 ERROR asdf a=b
Testing

The slogtest package provides utilities to make it easy to create loggers that will use the native testing logging.

func TestFoo(t *testing.T) {
	ctx := slogtest.TestContextWithLogger(t)

	for _, tc := range []string{"a", "b"} {
		t.Run(tc, func(t *testing.T) {
			slogctx.FromContext(ctx).Infof("hello world")
		})
	}
}
$ go test -v ./examples/logger
=== RUN   TestLog
=== RUN   TestLog/a
=== NAME  TestLog
    slogtest.go:20: time=2023-12-12T18:42:53.020-05:00 level=INFO msg="hello world"

=== RUN   TestLog/b
=== NAME  TestLog
    slogtest.go:20: time=2023-12-12T18:42:53.020-05:00 level=INFO msg="hello world"

--- PASS: TestLog (0.00s)
    --- PASS: TestLog/a (0.00s)
    --- PASS: TestLog/b (0.00s)
PASS
ok      github.com/wlynch/slogctx/examples/logger
Context Handler

The context Handler can be used to insert values from the context.

func init() {
	slog.SetDefault(slog.New(slogctx.NewHandler(slog.NewTextHandler(os.Stdout, nil))))
}

func main() {
	ctx := context.Background()
	ctx = slogctx.WithValue(ctx, "foo", "bar")

	// Use slog package directly
	slog.InfoContext(ctx, "hello world", slog.Bool("baz", true))

	// glog / zap style (note: can't pass additional attributes)
	slogctx.Errorf(ctx, "hello %s", "world")
}
$ go run .
time=2023-12-12T14:29:02.336-05:00 level=INFO msg="hello world" baz=true foo=bar
time=2023-12-12T14:29:02.337-05:00 level=ERROR msg="hello world" foo=bar

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug added in v1.1.0

func Debug(msg string, args ...any)

Debug calls Debug on the default logger.

func DebugContext added in v1.2.0

func DebugContext(ctx context.Context, msg string, args ...any)

DebugContext calls DebugContext on the context logger.

func DebugContextf added in v1.2.0

func DebugContextf(ctx context.Context, format string, args ...any)

DebugContextf calls DebugContextf on the context logger. If a Logger is found in the context, it will be used.

func Debugf added in v1.1.0

func Debugf(format string, args ...any)

Debugf calls Debugf on the default logger.

func Error added in v1.1.0

func Error(msg string, args ...any)

Error calls Error on the default logger.

func ErrorContext added in v1.2.0

func ErrorContext(ctx context.Context, msg string, args ...any)

ErrorContext calls ErrorContext on the context logger.

func ErrorContextf added in v1.2.0

func ErrorContextf(ctx context.Context, format string, args ...any)

ErrorContextf calls ErrorContextf on the context logger.

func Errorf added in v1.1.0

func Errorf(format string, args ...any)

Errorf calls Errorf on the default logger.

func Info added in v1.1.0

func Info(msg string, args ...any)

Info calls Info on the default logger.

func InfoContext added in v1.2.0

func InfoContext(ctx context.Context, msg string, args ...any)

InfoContext calls InfoContext on the context logger. If a Logger is found in the context, it will be used.

func InfoContextf added in v1.2.0

func InfoContextf(ctx context.Context, format string, args ...any)

InfoContextf calls InfoContextf on the context logger. If a Logger is found in the context, it will be used.

func Infof added in v1.1.0

func Infof(format string, args ...any)

Infof calls Infof on the default logger.

func Warn added in v1.1.0

func Warn(msg string, args ...any)

Warn calls Warn on the default logger.

func WarnContext added in v1.2.0

func WarnContext(ctx context.Context, msg string, args ...any)

WarnContext calls WarnContext on the context logger. If a Logger is found in the context, it will be used.

func WarnContextf added in v1.2.0

func WarnContextf(ctx context.Context, format string, args ...any)

WarnContextf calls WarnContextf on the context logger. If a Logger is found in the context, it will be used.

func Warnf added in v1.1.0

func Warnf(format string, args ...any)

Warnf calls Warnf on the default logger.

func WithLogger added in v1.2.0

func WithLogger(ctx context.Context, logger *Logger) context.Context

func WithValues added in v1.2.0

func WithValues(ctx context.Context, args ...any) context.Context

With returns a new context with the given values. Values are expected to be key-value pairs, where the key is a string. e.g. WithValues(ctx, "foo", "bar", "baz", 1) If a value already exists, it is overwritten. If an odd number of arguments are provided, With panics.

Types

type Handler

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

Handler is a slog.Handler that adds context values to the log record. Values are added via WithValues.

Example
package main

import (
	"context"
	"log/slog"
	"os"

	"github.com/wlynch/slogctx"
	"github.com/wlynch/slogctx/slogtest"
)

func main() {
	log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		// Remove time for repeatable results
		ReplaceAttr: slogtest.RemoveTime,
	}))

	ctx := context.Background()
	ctx = slogctx.WithValues(ctx, "foo", "bar")
	log.InfoContext(ctx, "hello world", slog.Bool("baz", true))

}
Output:

level=INFO msg="hello world" baz=true

func NewHandler

func NewHandler(h slog.Handler) Handler

NewHandler configures a new context aware slog handler. If h is nil, the default slog handler is used.

func (Handler) Enabled

func (h Handler) Enabled(ctx context.Context, level slog.Level) bool

func (Handler) Handle

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

func (Handler) WithAttrs

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

func (Handler) WithGroup

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

type Logger added in v1.2.0

type Logger struct {
	slog.Logger
}

Logger implements a wrapper around slog.Logger that adds formatter functions (e.g. Infof, Errorf)

Example
package main

import (
	"context"
	"log/slog"
	"os"

	"github.com/wlynch/slogctx"
	"github.com/wlynch/slogctx/slogtest"
)

func main() {
	log := slogctx.NewLogger(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		// Remove time for repeatable results
		ReplaceAttr: slogtest.RemoveTime,
	})))
	log = log.With("a", "b")
	ctx := slogctx.WithLogger(context.Background(), log)

	// Grab logger from context and use
	// Note: this is a formatter aware method, not an slog.Attr method.
	slogctx.FromContext(ctx).With("foo", "bar").Infof("hello %s", "world")

	// Package level context loggers are also aware
	slogctx.ErrorContext(ctx, "asdf", slog.Bool("baz", true))

}
Output:

level=INFO msg="hello world" a=b foo=bar
level=ERROR msg=asdf a=b baz=true

func DefaultLogger added in v1.2.0

func DefaultLogger() *Logger

DefaultLogger returns a new logger that uses the default slog.Logger.

func FromContext added in v1.2.0

func FromContext(ctx context.Context) *Logger

func New added in v1.2.0

func New(h slog.Handler) *Logger

New returns a new logger that wraps the given slog.Handler.

func NewLogger added in v1.2.0

func NewLogger(l *slog.Logger) *Logger

NewLogger returns a new logger that wraps the given slog.Logger.

func With

func With(args ...any) *Logger

With calls Logger.With on the default logger.

func (*Logger) Base added in v1.2.0

func (l *Logger) Base() *slog.Logger

Base returns the underlying slog.Logger.

func (*Logger) DebugContextf added in v1.2.0

func (l *Logger) DebugContextf(ctx context.Context, format string, args ...any)

DebugContextf logs at LevelDebug with the given context, format and arguments.

func (*Logger) Debugf added in v1.2.0

func (l *Logger) Debugf(format string, args ...any)

Debugf logs at LevelDebug with the given format and arguments.

func (*Logger) ErrorContextf added in v1.2.0

func (l *Logger) ErrorContextf(ctx context.Context, format string, args ...any)

ErrorContextf logs at LevelError with the given context, format and arguments.

func (*Logger) Errorf added in v1.2.0

func (l *Logger) Errorf(format string, args ...any)

Errorf logs at LevelError with the given format and arguments.

func (*Logger) Handler added in v1.2.1

func (l *Logger) Handler() slog.Handler

Handler returns the underlying slog.Handler.

func (*Logger) InfoContextf added in v1.2.0

func (l *Logger) InfoContextf(ctx context.Context, format string, args ...any)

InfoContextf logs at LevelInfo with the given context, format and arguments.

func (*Logger) Infof added in v1.2.0

func (l *Logger) Infof(format string, args ...any)

Infof logs at LevelInfo with the given format and arguments.

func (*Logger) WarnContextf added in v1.2.0

func (l *Logger) WarnContextf(ctx context.Context, format string, args ...any)

WarnContextf logs at LevelWarn with the given context, format and arguments.

func (*Logger) Warnf added in v1.2.0

func (l *Logger) Warnf(format string, args ...any)

Warnf logs at LevelWarn with the given format and arguments.

func (*Logger) With added in v1.2.0

func (l *Logger) With(args ...any) *Logger

With calls Logger.With on the logger.

func (*Logger) WithGroup added in v1.2.1

func (l *Logger) WithGroup(name string) *Logger

WithGroup calls Logger.WithGroup on the default logger.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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