Skip to content

Commit

Permalink
Merge pull request #14 from etkecc/master
Browse files Browse the repository at this point in the history
add breadcrumbs support
  • Loading branch information
archdx authored Dec 20, 2023
2 parents 9a0b4be + 3f53baa commit a41ff05
Showing 1 changed file with 50 additions and 14 deletions.
64 changes: 50 additions & 14 deletions writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -188,6 +215,7 @@ type config struct {
environment string
serverName string
ignoreErrors []string
breadcrumbs bool
debug bool
tracing bool
debugWriter io.Writer
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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
}

Expand Down

0 comments on commit a41ff05

Please sign in to comment.