1
0
Fork 0
mirror of https://github.com/chainguard-dev/clog synced 2026-07-06 22:12:46 +00:00
No description
Find a file
2023-12-12 18:30:25 -05:00
examples Add context logger. 2023-12-12 18:29:22 -05:00
.gitignore Initial commit 2023-12-06 16:21:07 -07:00
go.mod Initial commit 2023-12-06 16:31:14 -07:00
handler.go Add context logger. 2023-12-12 18:29:22 -05:00
handler_test.go Add context logger. 2023-12-12 18:29:22 -05:00
LICENSE Initial commit 2023-12-06 16:21:07 -07:00
log.go Add context logger. 2023-12-12 18:29:22 -05:00
logger.go Add context logger. 2023-12-12 18:29:22 -05:00
logger_test.go Add context logger. 2023-12-12 18:29:22 -05:00
README.md Add godoc badge 2023-12-12 18:30:25 -05:00

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

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