-
Notifications
You must be signed in to change notification settings - Fork 3
/
logging_slog.go
96 lines (76 loc) · 1.83 KB
/
logging_slog.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
91
92
93
94
95
96
//go:build go1.21
package fauna
import (
"context"
"log/slog"
"net/http"
"os"
"strconv"
)
type Logger interface {
Debug(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
LogResponse(ctx context.Context, requestBody []byte, r *http.Response)
}
type ClientLogger struct {
Logger
logger *slog.Logger
}
func (d ClientLogger) Debug(msg string, args ...any) {
if d.logger == nil {
return
}
d.logger.Debug(msg, args...)
}
func (d ClientLogger) Info(msg string, args ...any) {
if d.logger == nil {
return
}
d.logger.Info(msg, args...)
}
func (d ClientLogger) Warn(msg string, args ...any) {
if d.logger == nil {
return
}
d.logger.Warn(msg, args...)
}
func (d ClientLogger) Error(msg string, args ...any) {
if d.logger == nil {
return
}
d.logger.Error(msg, args...)
}
func (d ClientLogger) LogResponse(ctx context.Context, requestBody []byte, r *http.Response) {
if d.logger == nil {
return
}
requestLogger := d.logger.With(
slog.String("method", r.Request.Method),
slog.String("url", r.Request.URL.String()),
slog.Int("status", r.StatusCode))
headers := r.Request.Header
if _, found := headers["Authorization"]; found {
headers["Authorization"] = []string{"hidden"}
}
if d.logger.Enabled(ctx, slog.LevelDebug) {
requestLogger = requestLogger.With(
slog.String("requestBody", string(requestBody)),
)
}
requestLogger.With(
slog.Any("headers", headers)).Info("HTTP Response")
}
// DefaultLogger returns the default logger
func DefaultLogger() Logger {
clientLogger := ClientLogger{}
if val, found := os.LookupEnv(EnvFaunaDebug); found {
if level, _ := strconv.Atoi(val); level >= -4 {
clientLogger.logger = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.Level(level),
}))
}
}
return clientLogger
}