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

feat: http client integration #876

Open
wants to merge 17 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
# Changelog

## Unreleased

### Features

- Add `sentryzerolog` integration ([#857](https://github.com/getsentry/sentry-go/pull/857))
- Add `sentryslog` integration ([#865](https://github.com/getsentry/sentry-go/pull/865))
- Add net/http client integration ([#876](https://github.com/getsentry/sentry-go/pull/876))
- Always set Mechanism Type to generic ([#896](https://github.com/getsentry/sentry-go/pull/897))

### Misc
Expand Down
75 changes: 75 additions & 0 deletions _examples/httpclient/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package main

import (
"context"
"fmt"
"io"
"net/http"

"github.com/getsentry/sentry-go"
sentryhttpclient "github.com/getsentry/sentry-go/httpclient"
)

func main() {
_ = sentry.Init(sentry.ClientOptions{
Dsn: "",
EnableTracing: true,
TracesSampleRate: 1.0,
BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
fmt.Println(event)
return event
},
BeforeSendTransaction: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
fmt.Println(event)
return event
},
Debug: true,
})

// With custom HTTP client
ctx := sentry.SetHubOnContext(context.Background(), sentry.CurrentHub().Clone())
httpClient := &http.Client{
Transport: sentryhttpclient.NewSentryRoundTripper(nil),
}

err := getExamplePage(ctx, httpClient)
if err != nil {
panic(err)
}

// With Sentry's HTTP client
err = getExamplePage(ctx, sentryhttpclient.SentryHTTPClient)
if err != nil {
panic(err)
}
}

func getExamplePage(ctx context.Context, httpClient *http.Client) error {
span := sentry.StartSpan(ctx, "getExamplePage")
ctx = span.Context()
defer span.Finish()

request, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com", nil)
if err != nil {
return err
}

response, err := httpClient.Do(request)
if err != nil {
return err
}
defer func() {
if response.Body != nil {
_ = response.Body.Close()
}
}()

body, err := io.ReadAll(response.Body)
if err != nil {
return err
}

fmt.Println(string(body))

return nil
}
2 changes: 2 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ type ClientOptions struct {
TracesSampleRate float64
// Used to customize the sampling of traces, overrides TracesSampleRate.
TracesSampler TracesSampler
// Control with URLs trace propagation should be enabled. Does not support regex patterns.
TracePropagationTargets []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
140 changes: 140 additions & 0 deletions httpclient/sentryhttpclient.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// Package sentryhttpclient provides Sentry integration for Requests modules to enable distributed tracing between services.
// It is compatible with `net/http.RoundTripper`.
//
// import sentryhttpclient "github.com/getsentry/sentry-go/httpclient"
//
// roundTrippper := sentryhttpclient.NewSentryRoundTripper(nil, nil)
// client := &http.Client{
// Transport: roundTripper,
// }
//
// request, err := client.Do(request)
package sentryhttpclient

import (
"fmt"
"net/http"
"strings"

"github.com/getsentry/sentry-go"
)

// SentryRoundTripTracerOption provides a specific type in which defines the option for SentryRoundTripper.
type SentryRoundTripTracerOption func(*SentryRoundTripper)

// WithTracePropagationTargets configures additional trace propagation targets URL for the RoundTripper.
// Does not support regex patterns.
func WithTracePropagationTargets(targets []string) SentryRoundTripTracerOption {
return func(t *SentryRoundTripper) {
if t.tracePropagationTargets == nil {
t.tracePropagationTargets = targets
} else {
t.tracePropagationTargets = append(t.tracePropagationTargets, targets...)
}
}
}

// NewSentryRoundTripper provides a wrapper to existing http.RoundTripper to have required span data and trace headers for outgoing HTTP requests.
//
// - If `nil` is passed to `originalRoundTripper`, it will use http.DefaultTransport instead.
func NewSentryRoundTripper(originalRoundTripper http.RoundTripper, opts ...SentryRoundTripTracerOption) http.RoundTripper {
if originalRoundTripper == nil {
originalRoundTripper = http.DefaultTransport
}

// Configure trace propagation targets
var tracePropagationTargets []string
if hub := sentry.CurrentHub(); hub != nil {

Check failure on line 47 in httpclient/sentryhttpclient.go

View workflow job for this annotation

GitHub Actions / Lint

undefined: sentry (typecheck)
client := hub.Client()
if client != nil {
clientOptions := client.Options()
if clientOptions.TracePropagationTargets != nil {
tracePropagationTargets = clientOptions.TracePropagationTargets
}

}
}

t := &SentryRoundTripper{
originalRoundTripper: originalRoundTripper,
tracePropagationTargets: tracePropagationTargets,
}

for _, opt := range opts {
if opt != nil {
opt(t)
}
}

return t
}

// SentryRoundTripper provides a http.RoundTripper implementation for Sentry Requests module.
type SentryRoundTripper struct {
originalRoundTripper http.RoundTripper

tracePropagationTargets []string
}

func (s *SentryRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I wrote this, the docs said trace propagation targets is only for avoiding CORS-related issue, and since the dotnet SDK does not have that option too, I don't implement it here.

But is my assumption wrong here? Should all SDK implements trace propagation targets then?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes

// Respect trace propagation targets
if len(s.tracePropagationTargets) > 0 {
requestURL := request.URL.String()
foundMatch := false
for _, target := range s.tracePropagationTargets {
if strings.Contains(requestURL, target) {
foundMatch = true
break
}
}

if !foundMatch {
return s.originalRoundTripper.RoundTrip(request)
}
}

// Only create the `http.client` span only if there is a parent span.
parentSpan := sentry.SpanFromContext(request.Context())

Check failure on line 97 in httpclient/sentryhttpclient.go

View workflow job for this annotation

GitHub Actions / Lint

undefined: sentry (typecheck)
if parentSpan == nil {
if hub := sentry.GetHubFromContext(request.Context()); hub != nil {

Check failure on line 99 in httpclient/sentryhttpclient.go

View workflow job for this annotation

GitHub Actions / Lint

undefined: sentry (typecheck)
request.Header.Add("Baggage", hub.GetBaggage())
request.Header.Add("Sentry-Trace", hub.GetTraceparent())
}

return s.originalRoundTripper.RoundTrip(request)
}

cleanRequestURL := request.URL.Redacted()

span := parentSpan.StartChild("http.client", sentry.WithTransactionName(fmt.Sprintf("%s %s", request.Method, cleanRequestURL)))
defer span.Finish()

span.SetData("http.query", request.URL.Query().Encode())
span.SetData("http.fragment", request.URL.Fragment)
span.SetData("http.request.method", request.Method)
span.SetData("server.address", request.URL.Hostname())
span.SetData("server.port", request.URL.Port())

// Always add `Baggage` and `Sentry-Trace` headers.
request.Header.Add("Baggage", span.ToBaggage())
request.Header.Add("Sentry-Trace", span.ToSentryTrace())
Comment on lines +118 to +120
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To support the recently added "Tracing without Performance" feature, we should use hub.GetTraceparent() and hub.GetBaggage()


response, err := s.originalRoundTripper.RoundTrip(request)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We also want to handle the err case

if err != nil {
span.Status = sentry.SpanStatusInternalError
}

if response != nil {
span.Status = sentry.HTTPtoSpanStatus(response.StatusCode)
span.SetData("http.response.status_code", response.StatusCode)
span.SetData("http.response_content_length", response.ContentLength)
}

return response, err
}

// SentryHTTPClient provides a default HTTP client with SentryRoundTripper included.
// This can be used directly to perform HTTP request.
var SentryHTTPClient = &http.Client{
Transport: NewSentryRoundTripper(http.DefaultTransport),
}
Loading
Loading