-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathlogger.go
211 lines (179 loc) · 5.64 KB
/
logger.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package slogGorm
import (
"context"
"errors"
"fmt"
"log/slog"
"runtime"
"time"
"gorm.io/gorm"
gormlogger "gorm.io/gorm/logger"
"gorm.io/gorm/utils"
)
type LogType string
const (
ErrorLogType LogType = "sql_error"
SlowQueryLogType LogType = "slow_query"
DefaultLogType LogType = "default"
SourceField = "file"
ErrorField = "error"
QueryField = "query"
DurationField = "duration"
SlowQueryField = "slow_query"
RowsField = "rows"
)
// New creates a new logger for gorm.io/gorm
func New(options ...Option) *logger {
l := logger{
ignoreRecordNotFoundError: true,
errorField: ErrorField,
sourceField: SourceField,
// log levels
logLevel: map[LogType]slog.Level{
ErrorLogType: slog.LevelError,
SlowQueryLogType: slog.LevelWarn,
DefaultLogType: slog.LevelInfo,
},
// The default logger of gorm uses warn as its default level,
// see https://github.com/go-gorm/gorm/blob/master/logger/logger.go
gormLevel: gormlogger.Warn,
}
// Apply options
for _, option := range options {
option(&l)
}
if l.sloggerHandler == nil {
// If no sloggerHandler is defined, use the default Handler
l.sloggerHandler = slog.Default().Handler()
}
return &l
}
type logger struct {
sloggerHandler slog.Handler
ignoreTrace bool
ignoreRecordNotFoundError bool
traceAll bool
slowThreshold time.Duration
logLevel map[LogType]slog.Level
gormLevel gormlogger.LogLevel
contextKeys map[string]any
contextFuncs map[string]func(context.Context) (slog.Value, bool)
sourceField string
errorField string
}
// LogMode log mode
func (l logger) LogMode(level gormlogger.LogLevel) gormlogger.Interface {
// The Debug() function of gorm sets the log level to info for subsequent
// queries to trace them, see:
// https://gorm.io/docs/session.html#Debug
// The level is only retained to switch to logging all queries, whenever
// the level ist set to info.
l.gormLevel = level
// log level is set by slog
return l
}
// Info logs info
func (l logger) Info(ctx context.Context, format string, args ...any) {
l.log(ctx, slog.LevelInfo, format, args...)
}
// Warn logs warn messages
func (l logger) Warn(ctx context.Context, format string, args ...any) {
l.log(ctx, slog.LevelWarn, format, args...)
}
// Error logs error messages
func (l logger) Error(ctx context.Context, format string, args ...any) {
l.log(ctx, slog.LevelError, format, args...)
}
// log adds context attributes and logs a message with the given slog level
func (l logger) log(ctx context.Context, level slog.Level, format string, args ...any) {
if ctx == nil {
ctx = context.Background()
}
if !l.sloggerHandler.Enabled(ctx, level) {
return
}
// Properly handle the PC for the caller
var pc uintptr
var pcs [1]uintptr
// skip [runtime.Callers, this function, this function's caller]
runtime.Callers(3, pcs[:])
pc = pcs[0]
r := slog.NewRecord(time.Now(), level, fmt.Sprintf(format, args...), pc)
r.Add(l.appendContextAttributes(ctx, nil)...)
_ = l.sloggerHandler.Handle(ctx, r)
}
// log adds context attributes and logs a message with the given slog level
func (l logger) logAttrs(ctx context.Context, level slog.Level, msg string, attrs ...any) {
if ctx == nil {
ctx = context.Background()
}
if !l.sloggerHandler.Enabled(ctx, level) {
return
}
// Properly handle the PC for the caller
var pc uintptr
var pcs [1]uintptr
// skip [runtime.Callers, this function, this function's caller]
runtime.Callers(3, pcs[:])
pc = pcs[0]
r := slog.NewRecord(time.Now(), level, msg, pc)
r.Add(attrs...)
_ = l.sloggerHandler.Handle(ctx, r)
}
// Trace logs sql message
func (l logger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
if l.ignoreTrace {
return // Silent
}
elapsed := time.Since(begin)
switch {
case err != nil && (!errors.Is(err, gorm.ErrRecordNotFound) || !l.ignoreRecordNotFoundError):
sql, rows := fc()
// Append context attributes
attributes := l.appendContextAttributes(ctx, []any{
slog.Any(l.errorField, err),
slog.String(QueryField, sql),
slog.Duration(DurationField, elapsed),
slog.Int64(RowsField, rows),
slog.String(l.sourceField, utils.FileWithLineNum()),
})
l.logAttrs(ctx, l.logLevel[ErrorLogType], err.Error(), attributes...)
case l.slowThreshold != 0 && elapsed > l.slowThreshold:
sql, rows := fc()
// Append context attributes
attributes := l.appendContextAttributes(ctx, []any{
slog.Bool(SlowQueryField, true),
slog.String(QueryField, sql),
slog.Duration(DurationField, elapsed),
slog.Int64(RowsField, rows),
slog.String(l.sourceField, utils.FileWithLineNum()),
})
l.logAttrs(ctx, l.logLevel[SlowQueryLogType], fmt.Sprintf("slow sql query [%s >= %v]", elapsed, l.slowThreshold), attributes...)
case l.traceAll || l.gormLevel == gormlogger.Info:
sql, rows := fc()
// Append context attributes
attributes := l.appendContextAttributes(ctx, []any{
slog.String(QueryField, sql),
slog.Duration(DurationField, elapsed),
slog.Int64(RowsField, rows),
slog.String(l.sourceField, utils.FileWithLineNum()),
})
l.logAttrs(ctx, l.logLevel[DefaultLogType], fmt.Sprintf("SQL query executed [%s]", elapsed), attributes...)
}
}
func (l logger) appendContextAttributes(ctx context.Context, args []any) []any {
if args == nil {
args = []any{}
}
for k, v := range l.contextKeys {
if value := ctx.Value(v); value != nil {
args = append(args, slog.Any(k, value))
}
}
for k, f := range l.contextFuncs {
if value, ok := f(ctx); ok {
args = append(args, slog.Any(k, value))
}
}
return args
}