-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
55 lines (45 loc) · 1.1 KB
/
logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package gondola
import (
"context"
"log/slog"
"os"
"github.com/google/uuid"
)
// Logger is a logger.
type Logger struct {
*slog.Logger
}
// NewLogger creates a logger.
func NewLogger(level int) *Logger {
handler := TraceIDHandler{slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.Level(level),
})}
logger := slog.New(handler)
return &Logger{
logger,
}
}
// WithTraceID adds a trace ID to the context.
func WithTraceID(ctx context.Context) context.Context {
uuid, _ := uuid.NewRandom()
return context.WithValue(ctx, ctxTraceIDKey, uuid.String())
}
// GetTraceID returns a trace ID from the context.
func GetTraceID(ctx context.Context) string {
tid, _ := ctx.Value(ctxTraceIDKey).(string)
return tid
}
// TraceIDHandler is a handler for trace ID.
type TraceIDHandler struct {
slog.Handler
}
type ctxTraceID struct{}
var ctxTraceIDKey = ctxTraceID{}
// Handle adds a trace ID to the record.
func (t TraceIDHandler) Handle(ctx context.Context, r slog.Record) error {
tid := GetTraceID(ctx)
if tid != "" {
r.AddAttrs(slog.String("trace_id", tid))
}
return t.Handler.Handle(ctx, r)
}