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:45:04 -05:00
examples Add slogtest helpers. 2023-12-12 18:45:04 -05:00
slogtest Add slogtest helpers. 2023-12-12 18:45:04 -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 slogtest helpers. 2023-12-12 18:45:04 -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

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