slogctx means slog and context. It provides a simple way to log context information with the slog package.
go get github.com/akm/slogctx@latest
You can register your preparing function like this:
slogctx.Add(func(ctx context.Context, rec slog.Record) slog.Record {
val, ok := ctx.Value(ctxKey1).(string)
if ok {
rec.Add("key1", val)
}
return rec
})And you can get a logger working with your handle function by using slogctx.New instead of slog.New .
handler := slog.NewTextHandler(writer, nil)
logger := slogctx.New(handler)writer must be a io.Writer like os.Stdout, bytes.Buffer or etc.
ctx := context.WithValue(context.Background(), ctxKey1, "value1")
logger.InfoContext(ctx, "foo")Then logger outputs a log with foo as msg and value1 as key1 like this:
time=2024-12-21T12:18:51.893+09:00 level=INFO msg=foo key1=value1
See example_test.go for more detail.
- https://github.com/PumpkinSeed/slog-context
- Log all data in context.Context without specifying key
If you find a bug, typo, incorrect test, have an idea, or want to help with an existing issue, please create an issue or pull request.