-
Notifications
You must be signed in to change notification settings - Fork 9
/
sentry.go
568 lines (464 loc) · 17.2 KB
/
sentry.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
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
package sentryutil
import (
"context"
"fmt"
"reflect"
"time"
"github.com/mikeydub/go-gallery/service/logger"
"github.com/sirupsen/logrus"
"github.com/getsentry/sentry-go"
"github.com/gin-gonic/gin"
sentrygin "github.com/getsentry/sentry-go/gin"
"github.com/mikeydub/go-gallery/util"
)
const (
errorContextName = "error context"
loggerContextName = "logger context"
)
// SentryLoggerHook forwards log entries to Sentry.
var SentryLoggerHook = &sentryLoggerHook{crumbTrailLimit: sentryTrailLimit, reportLevels: logrus.AllLevels}
var logToSentryLevel = map[logrus.Level]sentry.Level{
logrus.PanicLevel: sentry.LevelFatal,
logrus.FatalLevel: sentry.LevelFatal,
logrus.ErrorLevel: sentry.LevelError,
logrus.WarnLevel: sentry.LevelWarning,
logrus.InfoLevel: sentry.LevelInfo,
logrus.DebugLevel: sentry.LevelDebug,
logrus.TraceLevel: sentry.LevelDebug,
}
var sentryTrailLimit = 8
// ReportRemappedError reports an error with additional context indicating the original error and the remapped error.
func ReportRemappedError(ctx context.Context, originalErr error, remappedErr interface{}) {
ReportError(ctx, originalErr, func(scope *sentry.Scope) {
if remappedErr != nil {
SetErrorContext(scope, true, fmt.Sprintf("%T", remappedErr))
scope.SetTag("remappedError", "true")
} else {
SetErrorContext(scope, false, "")
}
})
}
// ReportError reports an error with optional scope functions to add additional context.
func ReportError(ctx context.Context, err error, scopeFuncs ...func(*sentry.Scope)) {
hub := SentryHubFromContext(ctx)
if hub == nil {
logger.For(ctx).Warnln("could not report error to Sentry because hub is nil")
return
}
hub.WithScope(func(scope *sentry.Scope) {
for _, f := range scopeFuncs {
f(scope)
}
hub.CaptureException(err)
})
}
func ScrubEventHeaders(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
if event == nil || event.Request == nil {
return event
}
scrubbed := map[string]string{}
for k, v := range event.Request.Headers {
if k == "Authorization" {
scrubbed[k] = "[filtered]"
} else {
scrubbed[k] = v
}
}
event.Request.Headers = scrubbed
return event
}
func UpdateErrorFingerprints(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
if event == nil || hint == nil || hint.OriginalException == nil {
return event
}
if isErrErrorString(hint.OriginalException) {
event.Fingerprint = []string{"{{ default }}", hint.OriginalException.Error()}
}
return event
}
// UpdateLogErrorEvent updates the outgoing event with data from the logged error.
func UpdateLogErrorEvent(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
if wrapped, ok := hint.OriginalException.(logger.LoggedError); ok {
if wrapped.Err != nil {
if isErrErrorString(wrapped.Err) {
// Group by the actual error string so those errors are better categorized on Sentry.
event.Fingerprint = []string{"{{ type }}", wrapped.Err.Error()}
} else {
// Group first by the LoggedError type and further group by the actual wrapped error.
event.Fingerprint = []string{"{{ type }}", fmt.Sprintf("%T", wrapped.Err)}
}
mostRecent := len(event.Exception) - 1
event.Exception[mostRecent].Type = reflect.TypeOf(wrapped.Err).String()
// This really only works for errors created via the github.com/pkg/errors module.
if newStack := sentry.ExtractStacktrace(wrapped.Err); newStack != nil {
event.Exception[mostRecent].Stacktrace = newStack
}
}
}
return event
}
func SetErrorContext(scope *sentry.Scope, mapped bool, mappedTo string) {
errCtx := sentry.Context{
"Mapped": mapped,
"MappedTo": mappedTo,
}
scope.SetContext(errorContextName, errCtx)
}
// NewSentryHubGinContext returns a new Gin context with a cloned hub of the original context's hub.
// The hub is added to the context's request so that the sentrygin middleware is able to find it.
func NewSentryHubGinContext(ctx context.Context) *gin.Context {
cpy := util.MustGetGinContext(ctx).Copy()
if hub := SentryHubFromContext(cpy); hub != nil {
cpy.Request = cpy.Request.WithContext(sentry.SetHubOnContext(cpy.Request.Context(), hub.Clone()))
}
return cpy
}
// NewSentryHubContext returns a copy of the parent context with an instance of its hub attached.
// If no hub exists, the default hub stored in the global namespace is used. This
// is useful for separating sentry-related data when starting new goroutines.
func NewSentryHubContext(ctx context.Context) context.Context {
if hub := SentryHubFromContext(ctx); hub != nil {
return sentry.SetHubOnContext(ctx, hub.Clone())
}
return sentry.SetHubOnContext(ctx, sentry.CurrentHub().Clone())
}
// SentryHubFromContext gets a Hub from the supplied context, or from an underlying
// gin.Context if one is available.
func SentryHubFromContext(ctx context.Context) *sentry.Hub {
// Get a hub via Sentry's standard mechanism if possible
if hub := sentry.GetHubFromContext(ctx); hub != nil {
return hub
}
// Otherwise, see if there's a hub stored on the gin context
if gc := util.GetGinContext(ctx); gc != nil {
if hub := sentrygin.GetHubFromContext(gc); hub != nil {
return hub
}
// If not, try to get it from the request context
if hub := sentry.GetHubFromContext(gc.Request.Context()); hub != nil {
return hub
}
}
return nil
}
// sentryLoggerHook reports messages to Sentry.
type sentryLoggerHook struct {
crumbTrailLimit int
reportLevels []logrus.Level
}
// Levels returns the logging levels that the hook will fire on.
func (h sentryLoggerHook) Levels() []logrus.Level {
return h.reportLevels
}
// Fire reports the log entry to Sentry.
func (h sentryLoggerHook) Fire(entry *logrus.Entry) error {
if entry.Context == nil {
return nil
}
if hub := SentryHubFromContext(entry.Context); hub != nil {
switch isErr := entry.Level <= logrus.ErrorLevel; isErr {
// Send as an error
case true:
if scope := hub.Scope(); scope == nil {
hub.PushScope()
defer hub.PopScope()
}
// Add logger fields as a context
hub.Scope().SetContext(loggerContextName, entry.Data)
if err, ok := entry.Data[logrus.ErrorKey].(error); ok {
ReportError(entry.Context, logger.LoggedError{
Message: entry.Message,
Caller: entry.Caller,
Err: err,
})
} else {
ReportError(entry.Context, logger.LoggedError{
Message: entry.Message,
Caller: entry.Caller,
})
}
// Add to trail
default:
level := sentry.LevelDebug
if sentryLevel, ok := logToSentryLevel[entry.Level]; !ok {
level = sentryLevel
}
var category string
if entry.Caller != nil {
category = entry.Caller.Function
}
if scope := hub.Scope(); scope == nil {
hub.PushScope()
}
hub.Scope().AddBreadcrumb(&sentry.Breadcrumb{
Type: "default",
Category: category,
Level: level,
Message: entry.Message,
Data: entry.Data,
Timestamp: entry.Time,
}, h.crumbTrailLimit)
}
}
return nil
}
// RecoverAndRaise reports the panic to Sentry then re-raises it.
func RecoverAndRaise(ctx context.Context) {
if err := recover(); err != nil {
var hub *sentry.Hub
if ctx != nil {
hub = sentry.GetHubFromContext(ctx)
}
if hub == nil {
hub = sentry.CurrentHub()
}
if hub == nil {
panic(err)
}
defer sentry.Flush(2 * time.Second)
hub.Recover(err)
panic(err)
}
}
// TransactionNameSafe sets the name for the current transaction if a name is not already set.
func TransactionNameSafe(name string) sentry.SpanOption {
return func(s *sentry.Span) {
hub := sentry.GetHubFromContext(s.Context())
if hub == nil {
hub = sentry.CurrentHub()
}
if hub.Scope().Transaction() != "" {
return
}
sentry.TransactionName(name)(s)
}
}
func getSpanDuration(s *sentry.Span) time.Duration {
return s.EndTime.Sub(s.StartTime)
}
// Sentry uses milliseconds for its trace fields, and it keeps things consistent if we do it too
func durationToMsFloat(duration time.Duration) float64 {
return float64(duration.Microseconds()) / 1000.0
}
// SpanFilterEventProcessor applies a progressive filter to spans, removing the shortest spans until the total span count
// is less than the specified maxSpans value. Initially, spans shorter than minSpanDuration will be dropped, but each filter
// pass (up to maxFilterPasses) will double the minSpanDuration until enough spans have been filtered out.
// If alwaysFilter is specified, spans shorter than minSpanDuration will be removed, even if the total span count is low
// enough not to require any filtering.
func SpanFilterEventProcessor(ctx context.Context, maxSpans int, minSpanDuration time.Duration, maxFilterPasses int, alwaysFilter bool) sentry.EventProcessor {
return func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
if event == nil || event.Type != "transaction" || len(event.Spans) == 0 {
return event
}
type rollup struct {
Name string
RawSpans []*sentry.Span
Children map[string]*rollup
}
type spanData struct {
Parent *spanData
RawSpan *sentry.Span
IsFiltered bool
RollupsByName map[string]*rollup
Duration time.Duration
}
// Record how long the filtering process takes
spanFilterStartTime := time.Now()
spanDataBySpanID := make(map[sentry.SpanID]*spanData)
spans := make([]*spanData, 0, len(event.Spans))
for _, span := range event.Spans {
if span != nil {
sd := &spanData{RawSpan: span}
spanDataBySpanID[span.SpanID] = sd
spans = append(spans, sd)
}
}
for _, span := range spans {
span.Parent = spanDataBySpanID[span.RawSpan.ParentSpanID]
span.Duration = getSpanDuration(span.RawSpan)
}
// Propagate span times from child to parent.
// Use depth counter to avoid infinite looping if a cycle is encountered.
for _, span := range spans {
for depth := 0; depth < 1000; depth++ {
if span.Parent == nil {
break
}
child := span.RawSpan
parent := span.Parent.RawSpan
updatedParent := false
if child.EndTime.After(parent.EndTime) {
parent.EndTime = child.EndTime
updatedParent = true
}
// This generally shouldn't happen, but if it does, we still want the parent span to fully encapsulate its children
if child.StartTime.Before(parent.StartTime) {
logger.For(ctx).Warnf("child span '%s - %s' started at %v, before parent span '%s - %s' started at %v\n",
child.Op, child.Description, child.StartTime, parent.Op, parent.Description, parent.StartTime)
parent.StartTime = child.StartTime
updatedParent = true
}
if updatedParent {
// If the parent span has been updated, we should recalculate its duration to see if we should keep it
span.Parent.Duration = getSpanDuration(span.Parent.RawSpan)
}
span = span.Parent
}
}
var filteredSpans []*spanData
reportedFilterPasses := 0
reportedMinSpanDuration := time.Duration(0)
// Keep filtering and doubling the minSpanDuration until we've filtered out enough spans
for filterPass := 1; filterPass <= maxFilterPasses; filterPass++ {
if (!alwaysFilter || filterPass > 1) && len(spans) <= maxSpans {
break
}
logger.For(ctx).Infof("span filter pass %d, %d spans, minDurationForPass: %v\n", filterPass, len(spans), minSpanDuration)
allowedSpans := spans[:0]
for _, span := range spans {
// Spans without parents are always allowed
if span.Parent == nil || span.Duration > minSpanDuration {
allowedSpans = append(allowedSpans, span)
} else {
filteredSpans = append(filteredSpans, span)
span.IsFiltered = true
}
}
reportedFilterPasses = filterPass
reportedMinSpanDuration = minSpanDuration
spans = allowedSpans
minSpanDuration *= 2
}
var filterPath []*spanData
// Roll filtered spans up to their nearest unfiltered ancestor
for _, span := range filteredSpans {
filterPath = append(filterPath[:0], span)
span = span.Parent // will be non-nil, since filtered spans must have parents
// As above, use a depth counter to break cycles instead of infinite looping
for depth := 0; depth < 1000; depth++ {
if span.IsFiltered {
filterPath = append(filterPath, span)
span = span.Parent
continue
}
// We've reached the nearest allowed ancestor! Lazy initialize it.
if span.RollupsByName == nil {
span.RollupsByName = make(map[string]*rollup)
}
rollupsByName := span.RollupsByName
// Iterate backward so we're going from parent -> child
for i := len(filterPath) - 1; i >= 0; i-- {
filteredSpan := filterPath[i]
rawSpan := filteredSpan.RawSpan
var currentRollup *rollup
var ok bool
if currentRollup, ok = rollupsByName[rawSpan.Description]; !ok {
currentRollup = &rollup{Name: rawSpan.Description}
rollupsByName[rawSpan.Description] = currentRollup
}
// Only add the child span that's actively being rolled up; its parent spans (if any) will be
// added during their own roll-up step
if i == 0 {
currentRollup.RawSpans = append(currentRollup.RawSpans, rawSpan)
}
// If we haven't reached the final child span yet, make sure there's a map for the next
// level of rollup depth
if currentRollup.Children == nil && i > 0 {
currentRollup.Children = make(map[string]*rollup)
}
rollupsByName = currentRollup.Children
}
break
}
}
var getRollupStats func(*spanData, map[string]*rollup, map[string]interface{}) (time.Time, time.Time)
getRollupStats = func(rollupTo *spanData, rollupsByName map[string]*rollup, stats map[string]interface{}) (time.Time, time.Time) {
var rollupStart time.Time
var rollupEnd time.Time
// Get any child span to initialize the start and end times for the whole rollup
for _, r := range rollupsByName {
rollupStart = r.RawSpans[0].StartTime
rollupEnd = r.RawSpans[0].EndTime
break
}
// For every group of rolled up spans, figure out their containing interval (earliest start time to
// latest end time) and the average time per span.
for name, r := range rollupsByName {
intervalStart := r.RawSpans[0].StartTime
intervalEnd := r.RawSpans[0].EndTime
cumulativeDuration := time.Duration(0)
for _, s := range r.RawSpans {
if s.StartTime.Before(intervalStart) {
intervalStart = s.StartTime
}
if s.EndTime.After(intervalEnd) {
intervalEnd = s.EndTime
}
cumulativeDuration += getSpanDuration(s)
}
avgDuration := time.Duration(int64(cumulativeDuration) / int64(len(r.RawSpans)))
// Record interval start/end times relative to the parent span these are being rolled up to
relativeStart := intervalStart.Sub(rollupTo.RawSpan.StartTime)
relativeEnd := intervalEnd.Sub(rollupTo.RawSpan.StartTime)
statsForName := fmt.Sprintf("%s (%d) | %.3fms avg | [%.3fms - %.3fms] range", name, len(r.RawSpans),
durationToMsFloat(avgDuration), durationToMsFloat(relativeStart), durationToMsFloat(relativeEnd))
childStats := make(map[string]interface{})
stats[statsForName] = childStats
if r.Children != nil {
getRollupStats(rollupTo, r.Children, childStats)
}
if intervalStart.Before(rollupStart) {
rollupStart = intervalStart
}
if intervalEnd.After(rollupEnd) {
rollupEnd = intervalEnd
}
}
return rollupStart, rollupEnd
}
numUnfilteredSpans := len(event.Spans)
event.Spans = event.Spans[:0]
for _, span := range spans {
if span.RollupsByName != nil {
filteredSpanStats := make(map[string]interface{})
rollupStart, rollupEnd := getRollupStats(span, span.RollupsByName, filteredSpanStats)
if span.RawSpan.Data == nil {
span.RawSpan.Data = make(map[string]interface{})
}
data := span.RawSpan.Data
data["Filtered Spans"] = filteredSpanStats
data["Filtered Span Range"] = fmt.Sprintf("[%.3fms - %.3fms]", durationToMsFloat(rollupStart.Sub(span.RawSpan.StartTime)), durationToMsFloat(rollupEnd.Sub(span.RawSpan.StartTime)))
}
event.Spans = append(event.Spans, span.RawSpan)
}
timeTaken := time.Since(spanFilterStartTime)
filteredFrom := numUnfilteredSpans
filteredTo := len(event.Spans)
numDropped := 0
if filteredFrom != filteredTo {
logger.For(ctx).Infof("filtered %d spans down to %d spans in %v\n", filteredFrom, filteredTo, timeTaken)
}
// If we still have too many spans after filtering, we need to drop some
if len(event.Spans) > maxSpans {
numDropped = len(event.Spans) - maxSpans
logger.For(ctx).Warnf("dropping %d spans to reduce total from %d to %d\n", numDropped, len(event.Spans), maxSpans)
event.Spans = event.Spans[:maxSpans]
}
// Add filtering metadata to the event
event.Contexts["Span Filtering"] = map[string]interface{}{
"Filtering Took": fmt.Sprintf("%.3fms", durationToMsFloat(timeTaken)),
"Filtered From": fmt.Sprintf("%d spans", filteredFrom),
"Filtered To": fmt.Sprintf("%d spans", filteredTo),
"Dropped": fmt.Sprintf("%d spans", numDropped),
"Min Span Duration": fmt.Sprintf("%.3fms", durationToMsFloat(reportedMinSpanDuration)),
"Filter Passes": reportedFilterPasses,
}
return event
}
}
// This is a hacky way to do this -- we'd rather check the actual type than a string, but
// the errors.errorString type isn't exported and we'd really like a way to separate those
// errors on Sentry. It's not very useful to group every error created with errors.New().
func isErrErrorString(err error) bool {
return fmt.Sprintf("%T", err) == "*errors.errorString"
}