Skip to content

Repository files navigation

slogctx

CI codecov Enabled Linters Go Report Card Documentation license

slogctx means slog and context. It provides a simple way to log context information with the slog package.

Install

go get github.com/akm/slogctx@latest

Usage

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.

Alternatives

CONTRIBUTING

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.

LICENSE

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages