From 3f53baa3c58d64eca2db6317a479a17fb27d8184 Mon Sep 17 00:00:00 2001 From: Aine Date: Fri, 15 Dec 2023 14:03:15 +0200 Subject: [PATCH] add breadcrumbs support --- writer.go | 64 +++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 50 insertions(+), 14 deletions(-) diff --git a/writer.go b/writer.go index e7fee6f..d65476d 100644 --- a/writer.go +++ b/writer.go @@ -30,8 +30,31 @@ var now = time.Now type Writer struct { hub *sentry.Hub - levels map[zerolog.Level]struct{} - flushTimeout time.Duration + levels map[zerolog.Level]struct{} + flushTimeout time.Duration + withBreadcrumbs bool +} + +// addBreadcrumb adds event as a breadcrumb +func (w *Writer) addBreadcrumb(event *sentry.Event) { + if !w.withBreadcrumbs { + return + } + + // category is totally optional, but it's nice to have + var category string + if _, ok := event.Extra["category"]; ok { + if v, ok := event.Extra["category"].(string); ok { + category = v + } + } + + w.hub.AddBreadcrumb(&sentry.Breadcrumb{ + Category: category, + Message: event.Message, + Level: event.Level, + Data: event.Extra, + }, nil) } // Write handles zerolog's json and sends events to sentry. @@ -43,19 +66,23 @@ func (w *Writer) Write(data []byte) (n int, err error) { return n, nil } - if _, enabled := w.levels[lvl]; !enabled { + event, ok := w.parseLogEvent(data) + event.Level = levelsMapping[lvl] + + if !ok { return } - event, ok := w.parseLogEvent(data) - event.Level = levelsMapping[lvl] + if _, enabled := w.levels[lvl]; !enabled { + // if the level is not enabled, add event as a breadcrumb + w.addBreadcrumb(event) + return + } - if ok { - w.hub.CaptureEvent(event) - // should flush before os.Exit - if event.Level == sentry.LevelFatal { - w.hub.Flush(w.flushTimeout) - } + w.hub.CaptureEvent(event) + // should flush before os.Exit + if event.Level == sentry.LevelFatal { + w.hub.Flush(w.flushTimeout) } return @@ -188,6 +215,7 @@ type config struct { environment string serverName string ignoreErrors []string + breadcrumbs bool debug bool tracing bool debugWriter io.Writer @@ -245,6 +273,13 @@ func WithIgnoreErrors(reList []string) WriterOption { }) } +// WithBreadcrumbs enables sentry client breadcrumbs. +func WithBreadcrumbs() WriterOption { + return optionFunc(func(cfg *config) { + cfg.breadcrumbs = true + }) +} + // WithDebug enables sentry client debug logs. func WithDebug() WriterOption { return optionFunc(func(cfg *config) { @@ -350,9 +385,10 @@ func New(dsn string, opts ...WriterOption) (*Writer, error) { } return &Writer{ - hub: sentry.CurrentHub(), - levels: levels, - flushTimeout: cfg.flushTimeout, + hub: sentry.CurrentHub(), + levels: levels, + flushTimeout: cfg.flushTimeout, + withBreadcrumbs: cfg.breadcrumbs, }, nil }