-
Notifications
You must be signed in to change notification settings - Fork 2
/
logger.go
303 lines (245 loc) · 9.08 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package clog
import (
"context"
"fmt"
"io"
"log/slog"
"go.nownabe.dev/clog/errors"
"go.nownabe.dev/clog/internal/keys"
)
type Logger struct {
inner *slog.Logger
}
func New(w io.Writer, s Severity, json bool, opts ...Option) *Logger {
opt := &slog.HandlerOptions{
AddSource: false,
Level: s,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
a = replaceLevel(a)
a = replaceMessage(a)
return a
},
}
var h slog.Handler
if json {
h = slog.NewJSONHandler(w, opt)
} else {
h = slog.NewTextHandler(w, opt)
}
h = newLabelsHandler(h)
h = newOperationHandler(h)
for _, o := range opts {
h = o.apply(h)
}
return &Logger{slog.New(h)}
}
// Debug logs at SeverityDebug.
func (l *Logger) Debug(ctx context.Context, msg string, args ...any) {
l.log(ctx, SeverityDebug, msg, args...)
}
// Debugf logs formatted in the manner of fmt.Printf at SeverityDebug.
func (l *Logger) Debugf(ctx context.Context, format string, a ...any) {
l.log(ctx, SeverityDebug, fmt.Sprintf(format, a...))
}
// DebugErr logs an error at SeverityDebug.
func (l *Logger) DebugErr(ctx context.Context, err error, args ...any) {
l.err(ctx, SeverityDebug, err, args...)
}
// Info logs at SeverityInfo.
func (l *Logger) Info(ctx context.Context, msg string, args ...any) {
l.log(ctx, SeverityInfo, msg, args...)
}
// Infof logs formatted in the manner of fmt.Printf at SeverityInfo.
func (l *Logger) Infof(ctx context.Context, format string, a ...any) {
l.log(ctx, SeverityInfo, fmt.Sprintf(format, a...))
}
// InfoErr logs an error at SeverityInfo.
func (l *Logger) InfoErr(ctx context.Context, err error, args ...any) {
l.err(ctx, SeverityInfo, err, args...)
}
// Notice logs at SeverityNotice.
func (l *Logger) Notice(ctx context.Context, msg string, args ...any) {
l.log(ctx, SeverityNotice, msg, args...)
}
// Noticef logs formatted in the manner of fmt.Printf at SeverityNotice.
func (l *Logger) Noticef(ctx context.Context, format string, a ...any) {
l.log(ctx, SeverityNotice, fmt.Sprintf(format, a...))
}
// NoticeErr logs an error at SeverityNotice.
func (l *Logger) NoticeErr(ctx context.Context, err error, args ...any) {
l.err(ctx, SeverityNotice, err, args...)
}
// Warning logs at SeverityWarning.
func (l *Logger) Warning(ctx context.Context, msg string, args ...any) {
l.log(ctx, SeverityWarning, msg, args...)
}
// Warningf logs formatted in the manner of fmt.Printf at SeverityWarning.
func (l *Logger) Warningf(ctx context.Context, format string, a ...any) {
l.log(ctx, SeverityWarning, fmt.Sprintf(format, a...))
}
// WarningErr logs an error at SeverityWarning.
func (l *Logger) WarningErr(ctx context.Context, err error, args ...any) {
l.err(ctx, SeverityWarning, err, args...)
}
// Error logs at SeverityError.
func (l *Logger) Error(ctx context.Context, msg string, args ...any) {
l.log(ctx, SeverityError, msg, args...)
}
// Errorf logs formatted in the manner of fmt.Printf at SeverityError.
func (l *Logger) Errorf(ctx context.Context, format string, a ...any) {
l.log(ctx, SeverityError, fmt.Sprintf(format, a...))
}
// ErrorErr logs an error at SeverityError.
func (l *Logger) ErrorErr(ctx context.Context, err error, args ...any) {
l.err(ctx, SeverityError, err, args...)
}
// Critical logs at SeverityCritical.
func (l *Logger) Critical(ctx context.Context, msg string, args ...any) {
l.log(ctx, SeverityCritical, msg, args...)
}
// Criticalf logs formatted in the manner of fmt.Printf at SeverityCritical.
func (l *Logger) Criticalf(ctx context.Context, format string, a ...any) {
l.log(ctx, SeverityCritical, fmt.Sprintf(format, a...))
}
// CriticalErr logs an error at SeverityCritical.
func (l *Logger) CriticalErr(ctx context.Context, err error, args ...any) {
l.err(ctx, SeverityCritical, err, args...)
}
// Alert logs at SeverityAlert.
func (l *Logger) Alert(ctx context.Context, msg string, args ...any) {
l.log(ctx, SeverityAlert, msg, args...)
}
// Alertf logs formatted in the manner of fmt.Printf at SeverityAlert.
func (l *Logger) Alertf(ctx context.Context, format string, a ...any) {
l.log(ctx, SeverityAlert, fmt.Sprintf(format, a...))
}
// AlertErr logs an error at SeverityAlert.
func (l *Logger) AlertErr(ctx context.Context, err error, args ...any) {
l.err(ctx, SeverityAlert, err, args...)
}
// Emergency logs at SeverityEmergency.
func (l *Logger) Emergency(ctx context.Context, msg string, args ...any) {
l.log(ctx, SeverityEmergency, msg, args...)
}
// Emergencyf logs formatted in the manner of fmt.Printf at SeverityEmergency.
func (l *Logger) Emergencyf(ctx context.Context, format string, a ...any) {
l.log(ctx, SeverityEmergency, fmt.Sprintf(format, a...))
}
// EmergencyErr logs an error at SeverityEmergency.
func (l *Logger) EmergencyErr(ctx context.Context, err error, args ...any) {
l.err(ctx, SeverityEmergency, err, args...)
}
// Enabled reports whether the Logger emits log records at the given context and level.
func (l *Logger) Enabled(ctx context.Context, s Severity) bool {
return l.inner.Enabled(ctx, s)
}
// Err is a shorthand for ErrorErr.
func (l *Logger) Err(ctx context.Context, err error, args ...any) {
l.err(ctx, SeverityError, err, args...)
}
// Log emits a log record with the current time and the given level and message.
func (l *Logger) Log(ctx context.Context, s Severity, msg string, args ...any) {
l.log(ctx, s, msg, args...)
}
// With returns a Logger that includes the given attributes in each output operation.
func (l *Logger) With(args ...any) *Logger {
return &Logger{l.inner.With(args...)}
}
// HTTPReq emits a log with the given [HTTPRequest].
// The value of message field will be like "GET /foo HTTP/1.1".
// If status >= 500, the log is at SeverityError.
// Otherwise, the log is at SeverityInfo.
func (l *Logger) HTTPReq(ctx context.Context, req *HTTPRequest, args ...any) {
s := SeverityInfo
if req.Status >= 500 {
s = SeverityError
}
args = append(args, keys.HTTPRequest, req)
l.log(ctx, s, req.msg(), args...)
}
// WithInsertID returns a Logger that includes the given insertId in each output operation.
// See https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
func (l *Logger) WithInsertID(id string) *Logger {
return l.withAttrs(slog.String(keys.InsertID, id))
}
// StartOperation returns a new context and a function to end the opration, starting the operation.
// See https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogEntryOperation
func (l *Logger) StartOperation(
ctx context.Context, s Severity, msg, id, producer string,
) (context.Context, func(msg string)) {
return l.startOperation(ctx, s, msg, id, producer)
}
func (l *Logger) log(ctx context.Context, s Severity, msg string, args ...any) {
// skip [runtime.Callers, source, this function, clog exported function]
src := getSourceLocation(4)
l.logWithSource(ctx, s, src, msg, args...)
}
/*
func (l *Logger) logAttrs(ctx context.Context, s Severity, msg string, attrs ...slog.Attr) {
// skip [runtime.Callers, source, this function, clog exported function]
src := getSourceLocation(4)
l.logAttrsWithSource(ctx, s, src, msg, attrs...)
}
*/
func (l *Logger) startOperation(
ctx context.Context, s Severity, msg, id, producer string,
) (context.Context, func(msg string)) {
// skip [runtime.Callers, getSourceLocation, this function, exported function]
src := getSourceLocation(4)
l.logAttrsWithSource(ctx, s, src, msg, slog.Group(keys.Operation, "id", id, "producer", producer, "first", true))
opCtx := context.WithValue(ctx, ctxKeyOperation{}, &operation{id, producer})
return opCtx, func(msg string) {
l.logAttrsWithSource(ctx, s, src, msg, slog.Group(keys.Operation, "id", id, "producer", producer, "last", true))
}
}
func (l *Logger) withAttrs(attrs ...slog.Attr) *Logger {
return &Logger{slog.New(l.inner.Handler().WithAttrs(attrs))}
}
func (l *Logger) err(ctx context.Context, s Severity, err error, args ...any) {
if err == nil {
return
}
attrs := argsToAttrs(args)
var ews errors.ErrorWithStack
if errors.As(err, &ews) {
attrs = append(attrs, slog.String(keys.StackTrace, formatStack(ews)))
}
// skip [runtime.Callers, source, this function, clog exported function]
src := getSourceLocation(4)
l.logAttrsWithSource(ctx, s, src, err.Error(), attrs...)
}
func (l *Logger) logWithSource(ctx context.Context, s Severity, src *sourceLocation, msg string, args ...any) {
args = append(args, keys.SourceLocation, src)
l.inner.Log(ctx, s, msg, args...)
}
func (l *Logger) logAttrsWithSource(
ctx context.Context, s Severity, src *sourceLocation, msg string, attrs ...slog.Attr,
) {
attrs = append(attrs, slog.Any(keys.SourceLocation, src))
l.inner.LogAttrs(ctx, s, msg, attrs...)
}
func argsToAttrs(args []any) []slog.Attr {
const badKey = "!BADKEY"
var attrs []slog.Attr
for len(args) > 0 {
switch x := args[0].(type) {
case string:
if len(args) == 1 {
attrs = append(attrs, slog.String(badKey, x))
break
}
attrs = append(attrs, slog.Any(x, args[1]))
args = args[2:]
case slog.Attr:
attrs = append(attrs, x)
args = args[1:]
default:
attrs = append(attrs, slog.Any(badKey, x))
args = args[1:]
}
}
return attrs
}
func formatStack(e errors.ErrorWithStack) string {
return e.Error() + "\n\n" + string(e.Stack())
}