Repository navigation
Expand file tree
/
Copy pathentry.go
More file actions
506 lines (423 loc) · 13.1 KB
/
Copy pathentry.go
File metadata and controls
506 lines (423 loc) · 13.1 KB
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
package logrus
import (
"bytes"
"context"
"fmt"
"maps"
"os"
"reflect"
"runtime"
"strings"
"sync"
"time"
)
var (
// qualified package name, cached at first use
logrusPackage string
// Positions in the call stack when tracing to report the calling method.
//
// Start at the bottom of the stack before the package-name cache is primed.
minimumCallerDepth = 1
// Used for caller information initialisation
callerInitOnce sync.Once
)
const (
maximumCallerDepth int = 25
knownLogrusFrames int = 4
)
// ErrorKey defines the key when adding errors using [WithError], [Logger.WithError].
var ErrorKey = "error"
// Entry represents a single log event. It may be either an intermediate
// entry (created via WithField(s), WithContext, etc.) or a final entry
// that is emitted when one of the level methods (Trace, Debug, Info,
// Warn, Error, Fatal, Panic) is called.
//
// An Entry always belongs to a Logger. A nil Logger is invalid and will
// cause a panic when the entry is logged. Use [NewEntry] or Logger methods
// to construct entries.
//
// Entries are safe to reuse for adding fields and may be passed around
// to avoid field duplication. Each log operation operates on a copy
// of the Entry’s data to avoid mutation during formatting.
//
//nolint:recvcheck // Entry methods intentionally use both pointer and value receivers.
type Entry struct {
// Logger is the Logger that owns this entry and is responsible for
// formatting, hooks, and output. It must not be nil. An Entry without
// a Logger is invalid and will panic when logged.
Logger *Logger
// Data contains all user-defined fields attached to this entry.
Data Fields
// Time is the timestamp for the log event. If zero when the entry is
// logged, it defaults to the current time.
Time time.Time
// Level is the severity of the log entry. It is set when the entry
// is fired and reflects the level used for that log call.
Level Level
// Caller contains the calling method information when caller
// reporting is enabled.
Caller *runtime.Frame
// Message is the log message supplied to one of the logging methods
// (Trace, Debug, Info, Warn, Error, Fatal, or Panic). It is set when
// the entry is logged.
Message string
// Buffer is a reusable buffer provided to the formatter. It is set
// before formatting in the normal log path; when nil, formatters
// allocate their own.
Buffer *bytes.Buffer
// Context carries user-provided context for hooks and formatters.
Context context.Context
// err contains internal field-formatting errors.
err string
}
// NewEntry creates a new Entry associated with the provided Logger.
// The logger must not be nil. Passing a nil logger will result in a
// panic when a logging method (e.g., Info, Error, etc.) is called.
func NewEntry(logger *Logger) *Entry {
return &Entry{
Logger: logger,
// Reserve default predefined fields and a little extra room.
Data: make(Fields, defaultFields+3),
}
}
// Dup creates a copy of the entry for further modification.
//
// The Data map is cloned so that changes to fields on the returned
// entry do not mutate the original. The Logger and other metadata
// are copied by value.
func (entry *Entry) Dup() *Entry {
return &Entry{
Logger: entry.Logger,
Data: maps.Clone(entry.Data),
Time: entry.Time,
Context: entry.Context,
err: entry.err,
}
}
// Bytes returns the bytes representation of this entry from the formatter.
func (entry *Entry) Bytes() ([]byte, error) {
// Snapshot the formatter under the lock to protect against concurrent
// SetFormatter calls, then release the lock before formatting.
// This avoids a data race and prevents a deadlock if Format() triggers
// reentrant logging (e.g., a field's MarshalJSON calls logrus).
//
// See:
//
// - https://github.com/sirupsen/logrus/issues/1440
// - https://github.com/sirupsen/logrus/issues/1448
entry.Logger.mu.Lock()
formatter := entry.Logger.Formatter
entry.Logger.mu.Unlock()
return formatter.Format(entry)
}
// String returns the string representation from the reader and ultimately the
// formatter.
func (entry *Entry) String() (string, error) {
serialized, err := entry.Bytes()
if err != nil {
return "", err
}
str := string(serialized)
return str, nil
}
// WithError adds an error as single field (using the key defined in [ErrorKey])
// to the Entry.
func (entry *Entry) WithError(err error) *Entry {
// Avoid reflection work in WithFields; we know the type is an error;
// copy the entry data and set the ErrorKey directly.
data := make(Fields, len(entry.Data)+1)
maps.Copy(data, entry.Data)
data[ErrorKey] = err
return &Entry{
Logger: entry.Logger,
Data: data,
Time: entry.Time,
Context: entry.Context,
err: entry.err,
}
}
// WithContext adds a context to the Entry.
func (entry *Entry) WithContext(ctx context.Context) *Entry {
return &Entry{
Logger: entry.Logger,
Data: maps.Clone(entry.Data),
Time: entry.Time,
Context: ctx,
err: entry.err,
}
}
// WithField adds a single field to the Entry.
func (entry *Entry) WithField(key string, value any) *Entry {
return entry.WithFields(Fields{key: value})
}
// WithFields adds a map of fields to the Entry.
func (entry *Entry) WithFields(fields Fields) *Entry {
data := make(Fields, len(entry.Data)+len(fields))
maps.Copy(data, entry.Data)
fieldErr := entry.err
for k, v := range fields {
isErrField := false
if t := reflect.TypeOf(v); t != nil {
switch {
case t.Kind() == reflect.Func, t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.Func:
isErrField = true
}
}
if isErrField {
tmp := fmt.Sprintf("can not add field %q", k)
if fieldErr != "" {
fieldErr += ", " + tmp
} else {
fieldErr = tmp
}
} else {
data[k] = v
}
}
return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context}
}
// WithTime overrides the time of the Entry.
func (entry *Entry) WithTime(t time.Time) *Entry {
return &Entry{
Logger: entry.Logger,
Data: maps.Clone(entry.Data),
Time: t,
Context: entry.Context,
err: entry.err,
}
}
// getPackageName reduces a fully qualified function name to the package name
// There really ought to be a better way...
func getPackageName(f string) string {
for {
lastPeriod := strings.LastIndex(f, ".")
lastSlash := strings.LastIndex(f, "/")
if lastPeriod > lastSlash {
f = f[:lastPeriod]
} else {
break
}
}
return f
}
// getCaller retrieves the name of the first non-logrus calling function
func getCaller() *runtime.Frame {
// cache this package's fully-qualified name
callerInitOnce.Do(func() {
pcs := make([]uintptr, maximumCallerDepth)
_ = runtime.Callers(0, pcs)
// dynamic get the package name and the minimum caller depth
for i := range maximumCallerDepth {
funcName := runtime.FuncForPC(pcs[i]).Name()
if strings.Contains(funcName, "getCaller") {
logrusPackage = getPackageName(funcName)
break
}
}
minimumCallerDepth = knownLogrusFrames
})
// Restrict the lookback frames to avoid runaway lookups
pcs := make([]uintptr, maximumCallerDepth)
depth := runtime.Callers(minimumCallerDepth, pcs)
frames := runtime.CallersFrames(pcs[:depth])
for f, again := frames.Next(); again; f, again = frames.Next() {
pkg := getPackageName(f.Function)
// If the caller isn't part of this package, we're done
if pkg != logrusPackage {
return &f
}
}
// if we got here, we failed to find the caller's context
return nil
}
// HasCaller reports whether this Entry contains caller information.
//
// Caller is attached at log time if [Logger.ReportCaller] was enabled.
// In most cases, it is preferable to check whether [Entry.Caller] is nil
// directly.
func (entry Entry) HasCaller() bool {
return entry.Caller != nil
}
func (entry *Entry) log(level Level, msg string) {
newEntry := entry.Dup()
logger := newEntry.Logger
if newEntry.Time.IsZero() {
newEntry.Time = time.Now()
}
newEntry.Level = level
newEntry.Message = msg
logger.mu.Lock()
reportCaller := logger.ReportCaller
bufPool := newEntry.getBufferPool()
logger.mu.Unlock()
if reportCaller {
newEntry.Caller = getCaller()
}
// Select hooks based on the level for this log call. Hooks receive the
// Entry and may mutate it, but that does not affect which hooks are
// fired for this event.
hooks := logger.hooksForLevel(level)
newEntry.fireHooks(hooks)
buffer := bufPool.Get()
defer func() {
newEntry.Buffer = nil
buffer.Reset()
bufPool.Put(buffer)
}()
buffer.Reset()
newEntry.Buffer = buffer
newEntry.write()
newEntry.Buffer = nil
// To avoid Entry#log() returning a value that only would make sense for
// panic() to use in Entry#Panic(), we avoid the allocation by checking
// directly here.
if level <= PanicLevel {
panic(newEntry)
}
}
func (entry *Entry) getBufferPool() (pool BufferPool) {
if entry.Logger.BufferPool != nil {
return entry.Logger.BufferPool
}
return bufferPool
}
func (entry *Entry) fireHooks(hooks []Hook) {
for _, hook := range hooks {
if err := hook.Fire(entry); err != nil {
_, _ = fmt.Fprintln(os.Stderr, "Failed to fire hook:", err)
return
}
}
}
func (entry *Entry) write() {
// Snapshot the formatter under the lock to protect against concurrent
// SetFormatter calls, then release the lock before formatting.
// This avoids a deadlock when Format() triggers reentrant logging (e.g.,
// a field's MarshalJSON calls logrus). See #1448, #1440.
entry.Logger.mu.Lock()
formatter := entry.Logger.Formatter
entry.Logger.mu.Unlock()
serialized, err := formatter.Format(entry)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "Failed to format entry:", err)
return
}
// Re-acquire the lock to serialize writes to the underlying io.Writer.
entry.Logger.mu.Lock()
defer entry.Logger.mu.Unlock()
if _, err := entry.Logger.Out.Write(serialized); err != nil {
_, _ = fmt.Fprintln(os.Stderr, "Failed to write to log:", err)
}
}
// Log will log a message at the level given as parameter.
// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit.
// For this behaviour Entry.Panic or Entry.Fatal should be used instead.
func (entry *Entry) Log(level Level, args ...any) {
if entry.Logger.IsLevelEnabled(level) {
entry.log(level, fmt.Sprint(args...))
}
}
func (entry *Entry) Trace(args ...any) {
entry.Log(TraceLevel, args...)
}
func (entry *Entry) Debug(args ...any) {
entry.Log(DebugLevel, args...)
}
func (entry *Entry) Print(args ...any) {
entry.Info(args...)
}
func (entry *Entry) Info(args ...any) {
entry.Log(InfoLevel, args...)
}
func (entry *Entry) Warn(args ...any) {
entry.Log(WarnLevel, args...)
}
func (entry *Entry) Warning(args ...any) {
entry.Warn(args...)
}
func (entry *Entry) Error(args ...any) {
entry.Log(ErrorLevel, args...)
}
func (entry *Entry) Fatal(args ...any) {
entry.Log(FatalLevel, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panic(args ...any) {
entry.Log(PanicLevel, args...)
}
// Entry Printf family functions
func (entry *Entry) Logf(level Level, format string, args ...any) {
if entry.Logger.IsLevelEnabled(level) {
entry.Log(level, fmt.Sprintf(format, args...))
}
}
func (entry *Entry) Tracef(format string, args ...any) {
entry.Logf(TraceLevel, format, args...)
}
func (entry *Entry) Debugf(format string, args ...any) {
entry.Logf(DebugLevel, format, args...)
}
func (entry *Entry) Infof(format string, args ...any) {
entry.Logf(InfoLevel, format, args...)
}
func (entry *Entry) Printf(format string, args ...any) {
entry.Infof(format, args...)
}
func (entry *Entry) Warnf(format string, args ...any) {
entry.Logf(WarnLevel, format, args...)
}
func (entry *Entry) Warningf(format string, args ...any) {
entry.Warnf(format, args...)
}
func (entry *Entry) Errorf(format string, args ...any) {
entry.Logf(ErrorLevel, format, args...)
}
func (entry *Entry) Fatalf(format string, args ...any) {
entry.Logf(FatalLevel, format, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panicf(format string, args ...any) {
entry.Logf(PanicLevel, format, args...)
}
// Entry Println family functions
func (entry *Entry) Logln(level Level, args ...any) {
if entry.Logger.IsLevelEnabled(level) {
entry.Log(level, entry.sprintlnn(args...))
}
}
func (entry *Entry) Traceln(args ...any) {
entry.Logln(TraceLevel, args...)
}
func (entry *Entry) Debugln(args ...any) {
entry.Logln(DebugLevel, args...)
}
func (entry *Entry) Infoln(args ...any) {
entry.Logln(InfoLevel, args...)
}
func (entry *Entry) Println(args ...any) {
entry.Infoln(args...)
}
func (entry *Entry) Warnln(args ...any) {
entry.Logln(WarnLevel, args...)
}
func (entry *Entry) Warningln(args ...any) {
entry.Warnln(args...)
}
func (entry *Entry) Errorln(args ...any) {
entry.Logln(ErrorLevel, args...)
}
func (entry *Entry) Fatalln(args ...any) {
entry.Logln(FatalLevel, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panicln(args ...any) {
entry.Logln(PanicLevel, args...)
}
// sprintlnn => Sprint no newline. This is to get the behavior of how
// fmt.Sprintln where spaces are always added between operands, regardless of
// their type. Instead of vendoring the Sprintln implementation to spare a
// string allocation, we do the simplest thing.
func (entry *Entry) sprintlnn(args ...any) string {
msg := fmt.Sprintln(args...)
return msg[:len(msg)-1]
}