Skip to content

Instantly share code, notes, and snippets.

@rhcarvalho
Created June 15, 2021 15:02
Show Gist options
  • Save rhcarvalho/3dc943b4340851bc9d590b34661ebf03 to your computer and use it in GitHub Desktop.
Save rhcarvalho/3dc943b4340851bc9d590b34661ebf03 to your computer and use it in GitHub Desktop.
Sentry Go SDK - how to manually propagate traces in arbitrary programs
// This is an example program that demonstrates how to continue a Sentry trace
// for a hypothetical and arbitrary job runner, not a typical web server.
//
// Try it by running:
//
// go run main.go new
// go run main.go 55c41d7f4727204c592c87974aa1eedb-01ae7746826ce117-1
//
// To actually report events to Sentry, set the DSN either by editing the
// appropriate line below or setting the environment variable SENTRY_DSN to
// match the DSN of your Sentry project.
//
// The program will print a trace header that can be used to continue a trace in
// a subsequent execution. Passing any invalid string will simply ignore it and
// start a new trace.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/getsentry/sentry-go"
)
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, `usage:
Create a new trace:
%s new
Continue a trace (use the output from a previous run as argument):
%[1]s SENTRY-TRACE
Example:
%[1]s ae8bf3d6d16a2511be0172f32f0f92e6-92adb330ac553437-1
`, os.Args[0])
os.Exit(1)
}
log.SetPrefix("[Demo ] ")
err := sentry.Init(sentry.ClientOptions{
// Either set your DSN here or set the SENTRY_DSN environment variable.
Dsn: "",
// Enable printing of SDK debug messages.
// Useful when getting started or trying to figure something out.
Debug: true,
// Enable tracing.
TracesSampleRate: 1,
})
if err != nil {
log.Fatalf("sentry.Init: %s", err)
}
// Flush buffered events before the program terminates.
// Set the timeout to the maximum duration the program can afford to wait.
defer sentry.Flush(2 * time.Second)
sentryTrace := os.Args[1]
// At the moment the Go SDK only knows how to continue a trace from a
// request, so we fake one:
r := &http.Request{
Header: http.Header{"Sentry-Trace": {sentryTrace}},
}
ctx := context.Background()
span := sentry.StartSpan(ctx, "job",
sentry.TransactionName("job"),
sentry.ContinueFromRequest(r),
)
defer span.Finish()
// pretend we're doing some work
time.Sleep(500 * time.Millisecond)
log.Printf("Current job: %q", span.ToSentryTrace())
log.Printf("To simulate continuing the current trace, run: %s %s", os.Args[0], span.ToSentryTrace())
}
@rhcarvalho
Copy link
Author

Example trace after running the program twice:

Screen Shot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment