Custom Instrumentation

To instrument certain regions of your code, you can create transactions to capture them.

The following example creates a transaction span to time runs of an expensive operation on items from a channel. Timing for each operation is sent to Sentry and grouped by transaction name:

ctx := context.Background()

for item := range ch {
	span := sentry.StartSpan(ctx, "doWork",
		sentry.TransactionName(fmt.Sprintf("doWork: %s", item.Type)))
	doWork(span.Context(), item) // doWork may create additional spans

Add More Spans to the Transaction

The next example contains the implementation of the hypothetical doWork function called from the code snippet in the previous section. Our SDK can determine if there is currently an open transaction in the current context and add all newly created spans as child operations to that transaction. Keep in mind that each individual span also needs to be manually finished; otherwise, spans will not show up in the transaction.

You can choose the value of operation and description.

func doWork(ctx context.Context, item Item) {
	span := sentry.StartSpan(ctx, "suboperation1")
	// omitted code ...
	span := sentry.StartSpan(ctx, "suboperation2")
	// omitted code ...

All finished spans are sent together as a transaction when the root span is finished. Make sure to call Finish() appropriately. Often times defer span.Finish() is handy.

Retrieve a Transaction

In cases where you want to access the current transaction but don't have a direct reference to it, use sentry.TransactionFromContext. This function returns the root span of the current transaction, or nil if no transaction is started.

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    transaction := sentry.TransactionFromContext(ctx)
    cookie, _ := r.Cookie("secret")
    transaction.SetTag("secret-cookie", cookie.Value)
    // ...
You can edit this page on GitHub.