forked from tendermint/tendermint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracing_logger.go
76 lines (61 loc) · 1.7 KB
/
tracing_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
package log
import (
"fmt"
"github.com/pkg/errors"
)
// NewTracingLogger enables tracing by wrapping all errors (if they
// implement stackTracer interface) in tracedError.
//
// All errors returned by https://github.com/pkg/errors implement stackTracer
// interface.
//
// For debugging purposes only as it doubles the amount of allocations.
func NewTracingLogger(next Logger) Logger {
return &tracingLogger{
next: next,
}
}
type stackTracer interface {
error
StackTrace() errors.StackTrace
}
type tracingLogger struct {
next Logger
}
func (l *tracingLogger) Info(msg string, keyvals ...interface{}) {
l.next.Info(msg, formatErrors(keyvals)...)
}
func (l *tracingLogger) Debug(msg string, keyvals ...interface{}) {
l.next.Debug(msg, formatErrors(keyvals)...)
}
func (l *tracingLogger) Error(msg string, keyvals ...interface{}) {
l.next.Error(msg, formatErrors(keyvals)...)
}
func (l *tracingLogger) With(keyvals ...interface{}) Logger {
return &tracingLogger{next: l.next.With(formatErrors(keyvals)...)}
}
func formatErrors(keyvals []interface{}) []interface{} {
newKeyvals := make([]interface{}, len(keyvals))
copy(newKeyvals, keyvals)
for i := 0; i < len(newKeyvals)-1; i += 2 {
if err, ok := newKeyvals[i+1].(stackTracer); ok {
newKeyvals[i+1] = tracedError{err}
}
}
return newKeyvals
}
// tracedError wraps a stackTracer and just makes the Error() result
// always return a full stack trace.
type tracedError struct {
wrapped stackTracer
}
var _ stackTracer = tracedError{}
func (t tracedError) StackTrace() errors.StackTrace {
return t.wrapped.StackTrace()
}
func (t tracedError) Cause() error {
return t.wrapped
}
func (t tracedError) Error() string {
return fmt.Sprintf("%+v", t.wrapped)
}