-
Notifications
You must be signed in to change notification settings - Fork 22
/
slog.go
314 lines (265 loc) · 7.03 KB
/
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
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
304
305
306
307
308
309
310
311
312
313
314
// Package slog implements minimal structured logging.
//
// See https://cdr.dev/slog for overview docs and a comparison with existing libraries.
//
// The examples are the best way to understand how to use this library effectively.
//
// The Logger type implements a high level API around the Sink interface.
// Logger implements Sink as well to allow composition.
//
// Implementations of the Sink interface are available in the sloggers subdirectory.
package slog // import "cdr.dev/slog"
import (
"context"
"fmt"
"os"
"runtime"
"sync"
"time"
"go.opencensus.io/trace"
)
// Sink is the destination of a Logger.
//
// All sinks must be safe for concurrent use.
type Sink interface {
LogEntry(ctx context.Context, e SinkEntry)
Sync()
}
// LogEntry logs the given entry with the context to the
// underlying sinks.
//
// It extends the entry with the set fields and names.
func (l Logger) LogEntry(ctx context.Context, e SinkEntry) {
if e.Level < l.level {
return
}
e.Fields = l.fields.append(e.Fields)
e.LoggerNames = appendNames(l.names, e.LoggerNames...)
for _, s := range l.sinks {
s.LogEntry(ctx, e)
}
}
// Sync calls Sync on all the underlying sinks.
func (l Logger) Sync() {
for _, s := range l.sinks {
s.Sync()
}
}
// Logger wraps Sink with a nice API to log entries.
//
// Logger is safe for concurrent use.
type Logger struct {
sinks []Sink
level Level
names []string
fields Map
skip int
exit func(int)
}
// Make creates a logger that writes logs to the passed sinks at LevelInfo.
func Make(sinks ...Sink) Logger {
return Logger{
sinks: sinks,
level: LevelInfo,
exit: os.Exit,
}
}
// Debug logs the msg and fields at LevelDebug.
func (l Logger) Debug(ctx context.Context, msg string, fields ...Field) {
l.log(ctx, LevelDebug, msg, fields)
}
// Info logs the msg and fields at LevelInfo.
func (l Logger) Info(ctx context.Context, msg string, fields ...Field) {
l.log(ctx, LevelInfo, msg, fields)
}
// Warn logs the msg and fields at LevelWarn.
func (l Logger) Warn(ctx context.Context, msg string, fields ...Field) {
l.log(ctx, LevelWarn, msg, fields)
}
// Error logs the msg and fields at LevelError.
//
// It will then Sync().
func (l Logger) Error(ctx context.Context, msg string, fields ...Field) {
l.log(ctx, LevelError, msg, fields)
l.Sync()
}
// Critical logs the msg and fields at LevelCritical.
//
// It will then Sync().
func (l Logger) Critical(ctx context.Context, msg string, fields ...Field) {
l.log(ctx, LevelCritical, msg, fields)
l.Sync()
}
// Fatal logs the msg and fields at LevelFatal.
//
// It will then Sync() and os.Exit(1).
func (l Logger) Fatal(ctx context.Context, msg string, fields ...Field) {
l.log(ctx, LevelFatal, msg, fields)
l.Sync()
l.exit(1)
}
// With returns a Logger that prepends the given fields on every
// logged entry.
//
// It will append to any fields already in the Logger.
func (l Logger) With(fields ...Field) Logger {
l.fields = l.fields.append(fields)
return l
}
// Named appends the name to the set names
// on the logger.
func (l Logger) Named(name string) Logger {
l.names = appendNames(l.names, name)
return l
}
// Leveled returns a Logger that only logs entries
// equal to or above the given level.
func (l Logger) Leveled(level Level) Logger {
l.level = level
return l
}
func (l Logger) log(ctx context.Context, level Level, msg string, fields Map) {
ent := l.entry(ctx, level, msg, fields)
l.LogEntry(ctx, ent)
}
func (l Logger) entry(ctx context.Context, level Level, msg string, fields Map) SinkEntry {
ent := SinkEntry{
Time: time.Now().UTC(),
Level: level,
Message: msg,
Fields: fieldsFromContext(ctx).append(fields),
SpanContext: trace.FromContext(ctx).SpanContext(),
}
ent = ent.fillLoc(l.skip + 3)
return ent
}
var helpers sync.Map
// Helper marks the calling function as a helper
// and skips it for source location information.
// It's the slog equivalent of testing.TB.Helper().
func Helper() {
_, _, fn := location(1)
helpers.LoadOrStore(fn, struct{}{})
}
func (ent SinkEntry) fillFromFrame(f runtime.Frame) SinkEntry {
ent.Func = f.Function
ent.File = f.File
ent.Line = f.Line
return ent
}
func (ent SinkEntry) fillLoc(skip int) SinkEntry {
// Copied from testing.T
const maxStackLen = 50
var pc [maxStackLen]uintptr
// Skip two extra frames to account for this function
// and runtime.Callers itself.
n := runtime.Callers(skip+2, pc[:])
frames := runtime.CallersFrames(pc[:n])
for {
frame, more := frames.Next()
_, helper := helpers.Load(frame.Function)
if !helper || !more {
// Found a frame that wasn't a helper function.
// Or we ran out of frames to check.
return ent.fillFromFrame(frame)
}
}
}
func location(skip int) (file string, line int, fn string) {
pc, file, line, _ := runtime.Caller(skip + 1)
f := runtime.FuncForPC(pc)
return file, line, f.Name()
}
func appendNames(names []string, names2 ...string) []string {
if len(names2) == 0 {
return names
}
names3 := make([]string, 0, len(names)+len(names2))
names3 = append(names3, names...)
names3 = append(names3, names2...)
return names3
}
// Field represents a log field.
type Field struct {
Name string
Value interface{}
}
// F is a convenience constructor for Field.
func F(name string, value interface{}) Field {
return Field{Name: name, Value: value}
}
// M is a convenience constructor for Map
func M(fs ...Field) Map {
return fs
}
// Value represents a log value.
//
// Implement SlogValue in your own types to override
// the value encoded when logging.
type Value interface {
SlogValue() interface{}
}
// Error is the standard key used for logging a Go error value.
func Error(err error) Field {
return F("error", err)
}
type fieldsKey struct{}
func fieldsWithContext(ctx context.Context, fields Map) context.Context {
return context.WithValue(ctx, fieldsKey{}, fields)
}
func fieldsFromContext(ctx context.Context) Map {
l, _ := ctx.Value(fieldsKey{}).(Map)
return l
}
// With returns a context that contains the given fields.
//
// Any logs written with the provided context will have the given logs prepended.
//
// It will append to any fields already in ctx.
func With(ctx context.Context, fields ...Field) context.Context {
f1 := fieldsFromContext(ctx)
f2 := f1.append(fields)
return fieldsWithContext(ctx, f2)
}
// SinkEntry represents the structure of a log entry.
// It is the argument to the sink when logging.
type SinkEntry struct {
Time time.Time
Level Level
Message string
LoggerNames []string
Func string
File string
Line int
SpanContext trace.SpanContext
Fields Map
}
// Level represents a log level.
type Level int
// The supported log levels.
//
// The default level is Info.
const (
LevelDebug Level = iota
LevelInfo
LevelWarn
LevelError
LevelCritical
LevelFatal
)
var levelStrings = map[Level]string{
LevelDebug: "DEBUG",
LevelInfo: "INFO",
LevelWarn: "WARN",
LevelError: "ERROR",
LevelCritical: "CRITICAL",
LevelFatal: "FATAL",
}
// String implements fmt.Stringer.
func (l Level) String() string {
s, ok := levelStrings[l]
if !ok {
return fmt.Sprintf("slog.Level(%v)", int(l))
}
return s
}