Skip to content

Commit

Permalink
feat: allow passing context as event hint to sentry (#40)
Browse files Browse the repository at this point in the history
This allows sentry to extract existing trace information and link
events to their respective traces.
  • Loading branch information
costela authored Sep 13, 2023
1 parent dde0fb2 commit a204565
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
9 changes: 7 additions & 2 deletions core.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ func (c *core) Write(ent zapcore.Entry, fs []zapcore.Field) error {
}
}

var hint *sentry.EventHint

event := sentry.NewEvent()
event.Message = ent.Message
event.Timestamp = ent.Time
Expand All @@ -171,8 +173,11 @@ func (c *core) Write(ent zapcore.Entry, fs []zapcore.Field) error {
}
for _, f := range fs {
if f.Type == zapcore.SkipType {
if t, ok := f.Interface.(tagField); ok {
switch t := f.Interface.(type) {
case tagField:
event.Tags[t.Key] = t.Value
case ctxField:
hint = &sentry.EventHint{Context: t.Value}
}
}
}
Expand All @@ -186,7 +191,7 @@ func (c *core) Write(ent zapcore.Entry, fs []zapcore.Field) error {
}
}

_ = c.client.CaptureEvent(event, nil, c.scope())
_ = c.client.CaptureEvent(event, hint, c.scope())
}

// We may be crashing the program, so should flush any buffered events.
Expand Down
14 changes: 14 additions & 0 deletions field.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package zapsentry

import (
"context"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
Expand All @@ -13,3 +15,15 @@ type tagField struct {
func Tag(key string, value string) zap.Field {
return zap.Field{Key: key, Type: zapcore.SkipType, Interface: tagField{key, value}}
}

type ctxField struct {
Value context.Context
}

// Context adds a context to the logger.
// This can be used e.g. to pass trace information to sentry and allow linking events to their respective traces.
//
// See also https://docs.sentry.io/platforms/go/performance/instrumentation/opentelemetry/#linking-errors-to-transactions
func Context(ctx context.Context) zap.Field {
return zap.Field{Key: "context", Type: zapcore.SkipType, Interface: ctxField{ctx}}
}

0 comments on commit a204565

Please sign in to comment.