Categorygithub.com/akm/slogctx
repositorypackage
0.3.0
Repository: https://github.com/akm/slogctx.git
Documentation: pkg.go.dev

# Packages

No description provided by the author

# README

slogctx

CI codecov license

slogctx means slog and context. It supports to wrap the Handle method of slog.Handler interface.

Install

go get github.com/akm/slogctx@latest

Usage

You can register your handle function like this:

	slogctx.Register(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 .

    yourHandler := slog.NewTextHandler(writer, nil)
    yourLogger := slogctx.New(yourHandler)

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 examples/basic.go and examlpes/namespace.go for more detail. Try go run ./examples for go run ./examples/namespace