-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger_impl.go
217 lines (189 loc) · 5.67 KB
/
logger_impl.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
package logger
import (
"context"
"errors"
"fmt"
"github.com/getsentry/sentry-go"
"github.com/sirupsen/logrus"
"path/filepath"
"runtime"
"time"
)
// Keys used in log fields.
const (
ErrorKey = "error"
SpanIdLogKeyName = "spanID"
TraceIdLogKeyName = "traceID"
)
// baseLogger is our global base logger configuration.
var baseLogger *logrus.Logger
// init initializes a Logrus-based logger with JSON output, Debug level,
// no built-in caller info (we add our own).
func init() {
log := logrus.New()
log.SetFormatter(&logrus.JSONFormatter{
TimestampFormat: time.RFC3339Nano,
})
log.SetReportCaller(false)
log.SetLevel(logrus.DebugLevel)
baseLogger = log
}
// Log returns a logger instance potentially enriched with Sentry Trace and Span IDs
// extracted from the context if a Sentry span is active.
func Log(ctx context.Context) ILogger {
entry := logrus.NewEntry(baseLogger) // Start with a base entry for each call
fields := logrus.Fields{}
// Attempt to extract Sentry span context
if ctx != nil {
if span := sentry.SpanFromContext(getSentryContext(ctx)); span != nil {
traceID := span.TraceID.String()
spanID := span.SpanID.String()
if !isIdNull(traceID) && !isIdNull(spanID) {
fields[TraceIdLogKeyName] = traceID
fields[SpanIdLogKeyName] = spanID
}
}
}
// Return logger with potentially added Sentry fields
return &Logger{Entry: entry.WithFields(fields), Context: ctx}
}
// Logger is a Logrus-based ILogger.
type Logger struct {
Entry *logrus.Entry
Context context.Context
}
// SetLevel sets the log level for the underlying logger instance.
func (l *Logger) SetLevel(level logrus.Level) ILogger {
l.Entry.Logger.SetLevel(level)
return l
}
// Debug logs a message at debug level with optional fields.
func (l *Logger) Debug(msg string, keysAndValues ...interface{}) {
l.Entry.WithFields(l.convertToFields(keysAndValues...)).
WithField("caller", getCallerInfo()).
Debug(msg)
}
// Info logs a message at info level with optional fields.
func (l *Logger) Info(msg string, keysAndValues ...interface{}) {
l.Entry.WithFields(l.convertToFields(keysAndValues...)).
WithField("caller", getCallerInfo()).
Info(msg)
}
// Warn logs a message at warning level with optional fields.
func (l *Logger) Warn(msg string, keysAndValues ...interface{}) {
l.Entry.WithFields(l.convertToFields(keysAndValues...)).
WithField("caller", getCallerInfo()).
Warn(msg)
}
// Error logs a message at error level with optional fields.
// Sentry capture should happen explicitly where the error is handled using the context-aware hub.
func (l *Logger) Error(msg string, keysAndValues ...interface{}) {
l.captureErrors(msg)
fields := l.convertToFields(keysAndValues...)
l.Entry.WithFields(fields).
WithField("caller", getCallerInfo()).
Error(msg)
}
// Fatal logs a message at fatal level, then exits.
func (l *Logger) Fatal(msg string, keysAndValues ...interface{}) {
l.captureErrors(msg)
fields := l.convertToFields(keysAndValues...)
l.Entry.WithFields(fields).
WithField("caller", getCallerInfo()).
Fatal(msg)
}
// Panic logs a message at panic level, then panics.
func (l *Logger) Panic(msg string, keysAndValues ...interface{}) {
l.captureErrors(msg)
fields := l.convertToFields(keysAndValues...)
l.Entry.WithFields(fields).
WithField("caller", getCallerInfo()).
Panic(msg) // Note: Panic triggers a panic
}
// WithValues returns a new ILogger with additional fields added to the entry.
func (l *Logger) WithValues(keysAndValues ...interface{}) ILogger {
fields := l.convertToFields(keysAndValues...)
return &Logger{Entry: l.Entry.WithFields(fields), Context: l.Context}
}
// WithError returns a new ILogger that includes the given error in the log context.
func (l *Logger) WithError(err error) ILogger {
return &Logger{Entry: l.Entry.WithField(ErrorKey, err), Context: l.Context}
}
// convertToFields turns key-value pairs into Logrus fields.
func (l *Logger) convertToFields(keysAndValues ...interface{}) logrus.Fields {
fields := logrus.Fields{}
length := len(keysAndValues)
if length == 0 {
return fields
}
for i := 0; i < length-1; i += 2 {
key, ok := keysAndValues[i].(string)
if !ok {
key = fmt.Sprintf("invalid_key_%d", i)
}
fields[key] = keysAndValues[i+1]
}
if length%2 != 0 {
key, ok := keysAndValues[length-1].(string)
if !ok {
key = fmt.Sprintf("invalid_key_%d", length-1)
}
fields[key] = "MISSING_VALUE"
}
return fields
}
func (l *Logger) captureErrors(msg string) {
if l.Context == nil {
return
}
var hub *sentry.Hub
if h, ok := l.Context.Value(sentry.HubContextKey).(*sentry.Hub); ok {
hub = h
} else {
return
}
if msg != "" {
hub.CaptureException(errors.New(msg))
}
// Capture errors in fields
fields := l.Entry.Data
for _, value := range fields {
if err, isError := value.(error); isError {
hub.CaptureException(err)
}
}
}
// getCallerInfo returns file:line and function name for the calling code.
func getCallerInfo() string {
const skipFrames = 3
pc, file, line, ok := runtime.Caller(skipFrames)
if !ok {
return "unknown:?"
}
fn := runtime.FuncForPC(pc)
funcName := "unknown"
if fn != nil {
funcName = filepath.Base(fn.Name())
}
return fmt.Sprintf("%s:%d %s", filepath.Base(file), line, funcName)
}
// isIdNull checks if a trace or span ID string is effectively null (empty or all zeros).
func isIdNull(id string) bool {
if len(id) == 0 {
return true
}
for _, c := range id {
if c != '0' {
return false
}
}
return true
}
func getSentryContext(ctx context.Context) context.Context {
if sentryCtx, ok := ctx.Value(sentry.HubContextKey).(context.Context); ok {
return sentryCtx
}
return ctx
}
// Interface guard ensures Logger implements ILogger at compile time.
var _ ILogger = (*Logger)(nil)