logging update with context
This commit is contained in:
26
internal/logging/logging.go
Normal file
26
internal/logging/logging.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
)
|
||||
|
||||
type ContextHandler struct {
|
||||
slog.Handler
|
||||
}
|
||||
|
||||
func (h *ContextHandler) Handle(ctx context.Context, r slog.Record) error {
|
||||
if requestID, ok := ctx.Value("trace_id").(string); ok {
|
||||
r.AddAttrs(slog.String("trace_id", requestID))
|
||||
}
|
||||
return h.Handler.Handle(ctx, r)
|
||||
}
|
||||
|
||||
func NewLogger() *slog.Logger {
|
||||
baseHandler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{AddSource: false})
|
||||
customHandler := &ContextHandler{Handler: baseHandler}
|
||||
logger := slog.New(customHandler)
|
||||
|
||||
return logger
|
||||
}
|
||||
Reference in New Issue
Block a user