Created
March 5, 2024 20:24
-
-
Save ealyutikov/bae56222f752ae49aaa99383723342e6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "context" | |
| "log/slog" | |
| "maps" | |
| "os" | |
| "github.com/rs/zerolog" | |
| slogzerolog "github.com/samber/slog-zerolog" | |
| ) | |
| func main() { | |
| logCtx := map[string]string{ | |
| "request_id": "10746998-1b60-46bf-8a35-30f8158703c1", | |
| "user_id": "b9cf1fb6-b9ce-4d63-832e-a682595faf0e", | |
| "lol": "kek", | |
| } | |
| zeroLogger := zerolog.New(os.Stdout).Level(zerolog.InfoLevel) | |
| logger := slog.New(&ContextHandler{slogzerolog.Option{Logger: &zeroLogger}.NewZerologHandler()}) | |
| ctx := AppendSlogCtx(context.Background(), logCtx) | |
| logger.InfoContext(ctx, "info message") | |
| } | |
| type slogCtxKey struct{} | |
| type ContextHandler struct { | |
| slog.Handler | |
| } | |
| func (h ContextHandler) Handle(ctx context.Context, r slog.Record) error { | |
| if attrs, ok := ctx.Value(slogCtxKey{}).(map[string]string); ok { | |
| for k, v := range attrs { | |
| r.Add(slog.String(k, v)) | |
| } | |
| } | |
| return h.Handler.Handle(ctx, r) | |
| } | |
| func AppendSlogCtx(parent context.Context, attr map[string]string) context.Context { | |
| if parent == nil { | |
| parent = context.Background() | |
| } | |
| if v, ok := parent.Value(slogCtxKey{}).(map[string]string); ok { | |
| maps.Copy(v, attr) | |
| return context.WithValue(parent, slogCtxKey{}, v) | |
| } | |
| v := map[string]string{} | |
| maps.Copy(v, attr) | |
| return context.WithValue(parent, slogCtxKey{}, v) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment