-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathadapter.go
61 lines (51 loc) · 1.23 KB
/
adapter.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
package log
import (
"context"
"fmt"
"log/slog"
"github.com/jackc/pgx/v5/tracelog"
)
type Logger struct {
l *slog.Logger
invalidLevelKey string
}
type Option func(*Logger)
func WithInvalidLevelKey(key string) Option {
return func(l *Logger) {
l.invalidLevelKey = key
}
}
func NewLogger(l *slog.Logger, options ...Option) *Logger {
logger := &Logger{
l: l,
invalidLevelKey: "INVALID_PGX_LOG_LEVEL",
}
for _, option := range options {
option(logger)
}
return logger
}
func (l *Logger) Log(ctx context.Context, level tracelog.LogLevel, msg string, data map[string]interface{}) {
attrs := make([]slog.Attr, 0, len(data))
for k, v := range data {
attrs = append(attrs, slog.Any(k, v))
}
var lvl slog.Level
switch level {
case tracelog.LogLevelTrace:
lvl = slog.LevelDebug - 1
attrs = append(attrs, slog.Any("PGX_LOG_LEVEL", level))
case tracelog.LogLevelDebug:
lvl = slog.LevelDebug
case tracelog.LogLevelInfo:
lvl = slog.LevelInfo
case tracelog.LogLevelWarn:
lvl = slog.LevelWarn
case tracelog.LogLevelError:
lvl = slog.LevelError
default:
lvl = slog.LevelError
attrs = append(attrs, slog.Any(l.invalidLevelKey, fmt.Errorf("invalid pgx log level: %v", level)))
}
l.l.LogAttrs(ctx, lvl, msg, attrs...)
}