Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ref(otel): Add ClientOptions.Instrumenter #679

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,5 @@ TODO.md
# IDE system files
.idea
.vscode

/go.work*
11 changes: 11 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,9 @@ type ClientOptions struct {
TracesSampleRate float64
// Used to customize the sampling of traces, overrides TracesSampleRate.
TracesSampler TracesSampler
// Which instrumentation to use for tracing. Either "sentry" (default) or "otel" are supported.
// Setting this to "otel" will ignore TracesSampleRate and TracesSampler and assume sampling is performed by otel.
Instrumenter string
// The sample rate for profiling traces in the range [0.0, 1.0].
// This is relative to TracesSampleRate - it is a ratio of profiled traces out of all sampled traces.
ProfilesSampleRate float64
Expand Down Expand Up @@ -301,6 +304,14 @@ func NewClient(options ClientOptions) (*Client, error) {
options.MaxSpans = defaultMaxSpans
}

switch options.Instrumenter {
case "":
options.Instrumenter = "sentry"
case "sentry", "otel": // noop
default:
return nil, fmt.Errorf("invalid value for Instrumenter (supported are 'sentry' and 'otel'): %q", options.Instrumenter)
}

// SENTRYGODEBUG is a comma-separated list of key=value pairs (similar
// to GODEBUG). It is not a supported feature: recognized debug options
// may change any time.
Expand Down
14 changes: 14 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
pkgErrors "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -871,3 +872,16 @@ func TestClientSetsUpTransport(t *testing.T) {
client, _ = NewClient(ClientOptions{})
require.IsType(t, &noopTransport{}, client.Transport)
}

func TestClientSetupInstrumenter(t *testing.T) {
client, err := NewClient(ClientOptions{Dsn: ""})
require.NoError(t, err)
assert.Equal(t, "sentry", client.Options().Instrumenter)

_, err = NewClient(ClientOptions{Dsn: "", Instrumenter: "foo"})
require.Error(t, err)

client, err = NewClient(ClientOptions{Dsn: "", Instrumenter: "otel"})
require.NoError(t, err)
assert.Equal(t, "otel", client.Options().Instrumenter)
}
28 changes: 15 additions & 13 deletions fiber/sentryfiber.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,26 +74,28 @@ func (h *handler) handle(ctx *fiber.Ctx) error {
sentry.WithSpanOrigin(sentry.SpanOriginFiber),
}

transaction := sentry.StartTransaction(
sentry.SetHubOnContext(ctx.Context(), hub),
fmt.Sprintf("%s %s", method, transactionName),
options...,
)
if hub.Client().Options().Instrumenter == "sentry" {
transaction := sentry.StartTransaction(
sentry.SetHubOnContext(ctx.Context(), hub),
fmt.Sprintf("%s %s", method, transactionName),
options...,
)

defer func() {
status := ctx.Response().StatusCode()
transaction.Status = sentry.HTTPtoSpanStatus(status)
transaction.SetData("http.response.status_code", status)
transaction.Finish()
}()
defer func() {
status := ctx.Response().StatusCode()
transaction.Status = sentry.HTTPtoSpanStatus(status)
transaction.SetData("http.response.status_code", status)
transaction.Finish()
}()

transaction.SetData("http.request.method", method)
transaction.SetData("http.request.method", method)
ctx.Locals(transactionKey, transaction)
}

scope := hub.Scope()
scope.SetRequest(convertedHTTPRequest)
scope.SetRequestBody(ctx.Request().Body())
ctx.Locals(valuesKey, hub)
ctx.Locals(transactionKey, transaction)
defer h.recoverWithSentry(hub, ctx)
return ctx.Next()
}
Expand Down
30 changes: 17 additions & 13 deletions gin/sentrygin.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,19 +77,23 @@ func (h *handler) handle(c *gin.Context) {
sentry.WithSpanOrigin(sentry.SpanOriginGin),
}

transaction := sentry.StartTransaction(ctx,
fmt.Sprintf("%s %s", c.Request.Method, transactionName),
options...,
)
transaction.SetData("http.request.method", c.Request.Method)
defer func() {
status := c.Writer.Status()
transaction.Status = sentry.HTTPtoSpanStatus(status)
transaction.SetData("http.response.status_code", status)
transaction.Finish()
}()

c.Request = c.Request.WithContext(transaction.Context())
if hub.Client().Options().Instrumenter == "sentry" {
transaction := sentry.StartTransaction(ctx,
fmt.Sprintf("%s %s", c.Request.Method, transactionName),
options...,
)
transaction.SetData("http.request.method", c.Request.Method)
defer func() {
status := c.Writer.Status()
transaction.Status = sentry.HTTPtoSpanStatus(status)
transaction.SetData("http.response.status_code", status)
transaction.Finish()
}()
c.Request = c.Request.WithContext(transaction.Context())
} else {
c.Request = c.Request.WithContext(ctx) // we still need the context to get the hub
}

hub.Scope().SetRequest(c.Request)
c.Set(valuesKey, hub)
defer h.recoverWithSentry(hub, c.Request)
Expand Down
67 changes: 40 additions & 27 deletions gin/sentrygin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,20 @@ import (
"github.com/gin-gonic/gin"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/require"
)

func TestIntegration(t *testing.T) {
largePayload := strings.Repeat("Large", 3*1024) // 15 KB

tests := []struct {
RequestPath string
RoutePath string
Method string
WantStatus int
Body string
Handler gin.HandlerFunc
RequestPath string
RoutePath string
Method string
WantStatus int
Body string
Handler gin.HandlerFunc
Instrumenter string

WantEvent *sentry.Event
WantTransaction *sentry.Event
Expand Down Expand Up @@ -291,26 +293,20 @@ func TestIntegration(t *testing.T) {
},
WantEvent: nil,
},
{
RequestPath: "/404/1",
RoutePath: "/otel",
Method: "GET",
Instrumenter: "otel",
WantStatus: 404,
Handler: nil,
WantTransaction: nil,
WantEvent: nil,
},
}

eventsCh := make(chan *sentry.Event, len(tests))
transactionsCh := make(chan *sentry.Event, len(tests))
err := sentry.Init(sentry.ClientOptions{
EnableTracing: true,
TracesSampleRate: 1.0,
BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
eventsCh <- event
return event
},
BeforeSendTransaction: func(tx *sentry.Event, hint *sentry.EventHint) *sentry.Event {
fmt.Println("BeforeSendTransaction")
transactionsCh <- tx
return tx
},
})
if err != nil {
t.Fatal(err)
}

router := gin.New()
router.Use(sentrygin.New(sentrygin.Options{}))
Expand All @@ -329,17 +325,34 @@ func TestIntegration(t *testing.T) {
var wanttrans []*sentry.Event
var wantCodes []sentry.SpanStatus
for _, tt := range tests {
err := sentry.Init(sentry.ClientOptions{
EnableTracing: true,
TracesSampleRate: 1.0,
Instrumenter: tt.Instrumenter,
BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
eventsCh <- event
return event
},
BeforeSendTransaction: func(tx *sentry.Event, hint *sentry.EventHint) *sentry.Event {
transactionsCh <- tx
return tx
},
})
require.NoError(t, err)

if tt.WantEvent != nil && tt.WantEvent.Request != nil {
wantRequest := tt.WantEvent.Request
wantRequest.URL = srv.URL + wantRequest.URL
wantRequest.Headers["Host"] = srv.Listener.Addr().String()
want = append(want, tt.WantEvent)
}
wantTransaction := tt.WantTransaction.Request
wantTransaction.URL = srv.URL + wantTransaction.URL
wantTransaction.Headers["Host"] = srv.Listener.Addr().String()
wanttrans = append(wanttrans, tt.WantTransaction)
wantCodes = append(wantCodes, sentry.HTTPtoSpanStatus(tt.WantStatus))
if tt.WantTransaction != nil {
wantTransaction := tt.WantTransaction.Request
wantTransaction.URL = srv.URL + wantTransaction.URL
wantTransaction.Headers["Host"] = srv.Listener.Addr().String()
wanttrans = append(wanttrans, tt.WantTransaction)
wantCodes = append(wantCodes, sentry.HTTPtoSpanStatus(tt.WantStatus))
}

req, err := http.NewRequest(tt.Method, srv.URL+tt.RequestPath, strings.NewReader(tt.Body))
if err != nil {
Expand Down
45 changes: 25 additions & 20 deletions http/sentryhttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,29 +101,34 @@ func (h *Handler) handle(handler http.Handler) http.HandlerFunc {
sentry.WithSpanOrigin(sentry.SpanOriginStdLib),
}

transaction := sentry.StartTransaction(ctx,
fmt.Sprintf("%s %s", r.Method, r.URL.Path),
options...,
)
transaction.SetData("http.request.method", r.Method)

rw := NewWrapResponseWriter(w, r.ProtoMajor)

defer func() {
status := rw.Status()
transaction.Status = sentry.HTTPtoSpanStatus(status)
transaction.SetData("http.response.status_code", status)
transaction.Finish()
}()

// TODO(tracing): if the next handler.ServeHTTP panics, store
// information on the transaction accordingly (status, tag,
// level?, ...).
r = r.WithContext(transaction.Context())
if hub.Client().Options().Instrumenter == "sentry" {
transaction := sentry.StartTransaction(ctx,
fmt.Sprintf("%s %s", r.Method, r.URL.Path),
options...,
)
transaction.SetData("http.request.method", r.Method)

rw := NewWrapResponseWriter(w, r.ProtoMajor)
w = rw

defer func() {
status := rw.Status()
transaction.Status = sentry.HTTPtoSpanStatus(status)
transaction.SetData("http.response.status_code", status)
transaction.Finish()
}()

// TODO(tracing): if the next handler.ServeHTTP panics, store
// information on the transaction accordingly (status, tag,
// level?, ...).
r = r.WithContext(transaction.Context())
} else {
r = r.WithContext(ctx) // we still need the context to get the hub
}
hub.Scope().SetRequest(r)

defer h.recoverWithSentry(hub, r)
handler.ServeHTTP(rw, r)
handler.ServeHTTP(w, r)
}
}

Expand Down
57 changes: 57 additions & 0 deletions http/sentryhttp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
"github.com/getsentry/sentry-go/internal/testutils"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestIntegration(t *testing.T) {
Expand Down Expand Up @@ -356,3 +358,58 @@ func TestIntegration(t *testing.T) {
t.Fatalf("Transaction status codes mismatch (-want +got):\n%s", diff)
}
}

func TestInstrumenters(t *testing.T) {
tests := []struct {
instrumenter string
expectedEvents int
}{
{
instrumenter: "sentry",
expectedEvents: 1,
},
{
instrumenter: "otel",
expectedEvents: 0,
},
}

for _, tt := range tests {
t.Run(tt.instrumenter, func(t *testing.T) {
sentEvents := make(map[string]struct{})
err := sentry.Init(sentry.ClientOptions{
Dsn: "http://[email protected]/123",
Debug: true,
EnableTracing: true,
TracesSampleRate: 1.0,
Instrumenter: tt.instrumenter,
BeforeSendTransaction: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
sentEvents[string(event.EventID)] = struct{}{}
return event
},
})
require.NoError(t, err)

sentryHandler := sentryhttp.New(sentryhttp.Options{})
noopHandler := func(w http.ResponseWriter, r *http.Request) {}
srv := httptest.NewServer(sentryHandler.HandleFunc(noopHandler))
defer srv.Close()

c := srv.Client()
c.Timeout = time.Second

req, err := http.NewRequest("GET", srv.URL, http.NoBody)
require.NoError(t, err)

resp, err := c.Do(req)
require.NoError(t, err)
defer resp.Body.Close()

if ok := sentry.Flush(testutils.FlushTimeout()); !ok {
t.Fatal("sentry.Flush timed out")
}

assert.Equal(t, tt.expectedEvents, len(sentEvents), "wrong number of sent events")
})
}
}
Loading