Created
April 2, 2024 07:59
-
-
Save Karitham/2fda031a17da6fb1166184a11e77bf58 to your computer and use it in GitHub Desktop.
slog handler that pulls request id from context and adds it to traces
This file contains 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 http | |
import ( | |
"context" | |
"log/slog" | |
) | |
// RequestAttrGrabber adds an attribute to each row produced by the logger when it can | |
type RequestAttrGrabber struct { | |
Sub slog.Handler | |
AttrGrabber func(ctx context.Context) string | |
Key string | |
} | |
func (r RequestAttrGrabber) Enabled(ctx context.Context, l slog.Level) bool { | |
return r.Sub.Enabled(ctx, l) | |
} | |
func (r RequestAttrGrabber) Handle(ctx context.Context, rec slog.Record) error { | |
if id := r.AttrGrabber(ctx); id != "" { | |
rec.AddAttrs(slog.String(r.Key, id)) | |
} | |
return r.Sub.Handle(ctx, rec) | |
} | |
func (r RequestAttrGrabber) WithAttrs(attrs []slog.Attr) slog.Handler { | |
return RequestAttrGrabber{ | |
AttrGrabber: r.AttrGrabber, | |
Key: r.Key, | |
Sub: r.Sub.WithAttrs(attrs), | |
} | |
} | |
func (r RequestAttrGrabber) WithGroup(name string) slog.Handler { | |
return RequestAttrGrabber{ | |
AttrGrabber: r.AttrGrabber, | |
Key: r.Key, | |
Sub: r.Sub.WithGroup(name), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment