-
Notifications
You must be signed in to change notification settings - Fork 1
/
log.go
49 lines (44 loc) · 1011 Bytes
/
log.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
package util_log
import (
"log/slog"
"os"
)
type LogCfg struct {
MinLevel slog.Level
IncludeSrcLines bool
LoggerName string
}
func (l LogCfg) Default() LogCfg {
l.MinLevel = slog.LevelInfo
l.IncludeSrcLines = false
return l
}
func ConfigureGcpCompatibleJsonDefaultSlog(
cfg LogCfg,
) {
if cfg.LoggerName == "" {
cfg.LoggerName = "root"
}
slog.SetDefault(NewGcpCompatibleJsonSlog(cfg))
}
func NewGcpCompatibleJsonSlog(
cfg LogCfg,
) *slog.Logger {
result := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
AddSource: cfg.IncludeSrcLines,
Level: cfg.MinLevel,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if len(groups) == 0 && a.Key == "level" {
return slog.Attr{Key: "severity", Value: a.Value}
}
if len(groups) == 0 && a.Key == "msg" {
return slog.Attr{Key: "message", Value: a.Value}
}
return a
},
}))
if cfg.LoggerName != "" {
result = result.With(slog.String("logger", cfg.LoggerName))
}
return result
}