forked from phuslu/log
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger_go1.21.go
77 lines (67 loc) · 1.42 KB
/
logger_go1.21.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//go:build go1.21
// +build go1.21
package log
import (
"context"
"log/slog"
)
type slogHandler struct {
Logger
}
func (h *slogHandler) Enabled(_ context.Context, level slog.Level) bool {
switch level {
case slog.LevelDebug:
return h.Logger.Level <= DebugLevel
case slog.LevelInfo:
return h.Logger.Level <= InfoLevel
case slog.LevelWarn:
return h.Logger.Level <= WarnLevel
case slog.LevelError:
return h.Logger.Level <= ErrorLevel
}
return false
}
func (h *slogHandler) Handle(_ context.Context, r slog.Record) error {
var e *Entry
switch r.Level {
case slog.LevelDebug:
e = h.Logger.Debug()
case slog.LevelInfo:
e = h.Logger.Info()
case slog.LevelWarn:
e = h.Logger.Warn()
case slog.LevelError:
e = h.Logger.Error()
default:
e = h.Logger.Log()
}
r.Attrs(func(attr slog.Attr) bool {
e = e.Any(attr.Key, attr.Value)
return true
})
e.Msg(r.Message)
return nil
}
func (h *slogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
e := NewContext(nil)
for _, attr := range attrs {
e = e.Any(attr.Key, attr.Value)
}
l := h.Logger
l.Context = e.Value()
return &slogHandler{l}
}
func (h *slogHandler) WithGroup(name string) slog.Handler {
return h
}
// Slog wraps the Logger to provide *slog.Logger
func (l *Logger) Slog() *slog.Logger {
logger := *l
switch {
case logger.Caller > 0:
logger.Caller += 3
case logger.Caller < 0:
logger.Caller -= 3
}
return slog.New(&slogHandler{logger})
}