-
Notifications
You must be signed in to change notification settings - Fork 0
/
logging.go
90 lines (74 loc) · 1.97 KB
/
logging.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
78
79
80
81
82
83
84
85
86
87
88
89
90
package logging
import (
"context"
"log/slog"
"net/http"
"os"
"runtime/debug"
"github.com/altipla-consulting/env"
"github.com/altipla-consulting/errors"
"github.com/lmittmann/tint"
"github.com/altipla-consulting/telemetry"
"github.com/altipla-consulting/telemetry/internal/config"
)
func Standard() telemetry.Option {
return stdLevel(slog.LevelInfo)
}
func Debug() telemetry.Option {
return stdLevel(slog.LevelDebug)
}
func Trace() telemetry.Option {
return stdLevel(LevelTrace)
}
func stdLevel(level slog.Level) telemetry.Option {
return func(settings *config.Settings) {
settings.Collectors = append(settings.Collectors, new(logCollector))
if env.IsLocal() {
slog.SetDefault(slog.New(tint.NewHandler(os.Stderr, &tint.Options{
Level: level,
})))
return
}
logger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
Level: level,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
switch {
case a.Key == slog.MessageKey:
a.Key = "message"
case a.Key == slog.LevelKey:
a.Key = "severity"
switch level := a.Value.Any().(slog.Level); level {
// Map a different name for warnings.
case slog.LevelWarn:
a.Value = slog.StringValue("WARNING")
// Custom levels.
case LevelTrace:
a.Value = slog.StringValue("DEFAULT")
case LevelNotice:
a.Value = slog.StringValue("NOTICE")
case LevelCritical:
a.Value = slog.StringValue("CRITICAL")
}
}
return a
},
}))
slog.SetDefault(logger)
}
}
type logCollector struct{}
func (*logCollector) ReportError(ctx context.Context, err error) {
// empty
}
func (*logCollector) ReportErrorRequest(r *http.Request, err error) {
// empty
}
func (*logCollector) ReportPanic(ctx context.Context, panicErr any) {
rec := errors.Recover(panicErr)
slog.Error("Panic recovered",
slog.String("error", rec.Error()),
slog.String("details", errors.Details(rec)))
if env.IsLocal() {
slog.Error(string(debug.Stack()))
}
}