Skip to content

Commit

Permalink
feat(js): Update custom trace propagation docs (#12475)
Browse files Browse the repository at this point in the history

---------

Co-authored-by: Alex Krawiec <[email protected]>
Co-authored-by: Lukas Stracke <[email protected]>
  • Loading branch information
3 people authored Jan 28, 2025
1 parent f940420 commit 88da19d
Show file tree
Hide file tree
Showing 7 changed files with 196 additions and 229 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: Custom Instrumentation
title: Custom Span Instrumentation
description: "Learn how to capture performance data on any action in your app."
sidebar_order: 20
---
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: Custom Instrumentation
title: Custom Trace Propagation
sidebar_order: 40
notSupported:
- javascript.cordova
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ If the overall application landscape that you want to observe with Sentry consis

## What is Distributed Tracing?

In the context of tracing events across a distributed system, distributed tracing acts as a powerful debugging tool. Imagine your application as a vast network of interconnected parts. For example, your system might be spread across different servers or your application might split into different backend and frontend services, each potentially having their own technology stack.

When an error or performance issue occurs, it can be challenging to pinpoint the root cause due to the complexity of such a system. Distributed tracing helps you follow the path of an event as it travels through this intricate web, recording every step it takes. By examining these traces, you can reconstruct the sequence of events leading up to the event of interest, identify the specific components involved, and understand their interactions. This detailed visibility enables you to diagnose and resolve issues more effectively, ultimately improving the reliability and performance of your distributed system.
<PlatformContent includePath="distributed-tracing/explanation" />

## Basic Example

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
Distributed tracing will be set up automatically if you've <PlatformLink to="/tracing/">set up tracing</PlatformLink>.

<Expandable title="What is Distributed Tracing?">
<PlatformContent includePath="distributed-tracing/explanation" />
</Expandable>

When tracing is enabled, the Sentry SDK will not only create spans for pageloads and transactions but also propagate trace information to other systems. This allows you to connect multiple systems and see how they interact with each other.

By default, outgoing HTTP requests will automatically be instrumented for you. For other cases where you may want to continue traces (for example when working with websockets), you can manually extract and inject tracing information.

## Enabling Automatic Distributed Tracing

To enable distributed tracing for your frontend, add `browserTracingIntegration` to your `Sentry.init()` options as described in the <PlatformLink to="/tracing/instrumentation/automatic-instrumentation/">Automatic Instrumentation</PlatformLink> docs.

### Continuing a Trace Manually

By default, the `browserTracingIntegration` will automatically continue a trace found in a `<meta>` tag - see <PlatformLink to="/tracing/trace-propagation/#automatic-trace-propagation">Automatic Trace Propagation</PlatformLink> for details.
If you want to continue a different trace, for example because you cannot propagate the trace through meta tags but through some different mechanism, you can do this:

```javascript
const client = Sentry.init({
dsn: "___PUBLIC_DSN___",
integrations: [
Sentry.browserTracingIntegration({
// Disable default pageload instrumentation
instrumentPageLoad: false,
}),
],
});

// Start the pageload span manually
const sentryTrace = getSentryTraceStringFromSomewhere();
const baggage = getBaggageStringFromSomewhere();

Sentry.startBrowserTracingPageLoadSpan(
client,
{
name: window.location.pathname,
},
{ sentryTrace, baggage }
);
```

## Configuring Distributed Tracing Without `browserTracingIntegration`

If you don't want to use the `browserTracingIntegration` integration, or you want to propagate traces in other places than HTTP requests (for example, with websockets), you can manually extract and inject tracing data in your application to connect multiple systems. For this, you must:

- Extract and store incoming tracing information from HTML `<meta>` tags when loading the page.
- Inject tracing information to any outgoing requests.

To learn more about distributed tracing, see our <PlatformLink to="/tracing/trace-propagation/">Distributed Tracing</PlatformLink> docs.

### Extract Tracing Information From HTML `meta` Tags

If you have a server that renders your application's HTML (server-side rendering) and is also running a Sentry SDK, you can connect your backend to your backend via tracing.

To do this, have your server render HTML `<meta>` tags with the Sentry trace information. In your frontend, extract that tracing information when the page is loading and use it to create new transactions connected to that incoming backend trace.

Some Sentry backend SDKs provide a built-in way to inject these `<meta>` tags into rendered HTML. For example:

- [Node](/platforms/javascript/guides/node/tracing/trace-propagation/custom-instrumentation/#injecting-tracing-information-into-html)
- [Python](/platforms/python/distributed-tracing/custom-instrumentation/#inject-tracing-information-into-rendered-html)
- [Ruby](/platforms/ruby/distributed-tracing/custom-instrumentation/#inject-tracing-information-into-rendered-html)
- [PHP](/platforms/php/distributed-tracing/custom-instrumentation/#inject-tracing-information-into-rendered-html)

Then, on `pageload` you can do the following:

```javascript
import { propagationContextFromHeaders } from "@sentry/core"; // Before version 8.40.0, import from "@sentry/utils"
import * as Sentry from "@sentry/browser";

// Read meta tag values
const sentryTrace = document.querySelector("meta[name=sentry-trace]")?.content;
const baggage = document.querySelector("meta[name=baggage]")?.content;

// Generate a propagation context from the meta tags
const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
Sentry.getCurrentScope().setPropagationContext(propagationContext);

Sentry.startSpan(
{
name: `Pageload: ${window.location.pathname}`,
op: "pageload",
},
() => {
// do something
}
);
```
In this example, we create a new root span that is attached to the trace specified in the `sentry-trace` and `baggage` HTML `<meta>` tags.
Original file line number Diff line number Diff line change
@@ -1,174 +1,14 @@
On this page you will learn how to manually propagate trace information into and out of your JavaScript application.

Distributed tracing will be set up automatically if:

- You've <PlatformLink to="/tracing/">Set Up Tracing</PlatformLink>, or
- You're using one of the SDKs that include tracing propagation out of the box:
- `@sentry/astro`
- `@sentry/nextjs`
- `@sentry/nuxt`
- `@sentry/remix`
- `@sentry/solidstart`
- `@sentry/sveltekit`

If you are using a different package, and have not enabled tracing, you can manually set up your application for distributed tracing to work.

## Enabling Distributed Tracing

<PlatformCategorySection supported={['browser']}>

To enable distributed tracing for your frontend, add `browserTracingIntegration` to your `Sentry.init()` options as described in the <PlatformLink to="/tracing/instrumentation/automatic-instrumentation/">Automatic Instrumentation</PlatformLink> docs.

If you want to use distributed tracing but not tracing, set the `tracesSampleRate` option to `0`.

```javascript
Sentry.init({
dsn: "___PUBLIC_DSN___",
integrations: [Sentry.browserTracingIntegration()],

// If this is 0, tracing is disabled
// but distributed tracing is not
tracesSampleRate: 0,
});
```

### Continuing a Trace Manually

By default, the `browserTracingIntegration` will automatically continue a trace found in a `<meta>` tags - see <PlatformLink to="/tracing/trace-propagation/#automatic-trace-propagation">Automatic Trace Propagation</PlatformLink> for details.
If you want to continue a different trace, for example because you cannot propagate the trace through meta tags but through some different mechanism, you can do this as follows:

```javascript
const client = Sentry.init({
dsn: "___PUBLIC_DSN___",
integrations: [
Sentry.browserTracingIntegration({
// Disable default pageload instrumentation
instrumentPageLoad: false,
}),
],
});

// Start the pageload span manually
const sentryTrace = getSentryTraceStringFromSomewhere();
const baggage = getBaggageStringFromSomewhere();

Sentry.startBrowserTracingPageLoadSpan(
client,
{
name: window.location.pathname,
},
{ sentryTrace, baggage }
);
```

## Enabling Distributed Tracing without `browserTracingIntegration`

If you don't want to use the `browserTracingIntegration` integration, you can manually extract and inject tracing data in your application to connect multiple systems. For this, you must:

- Extract and store incoming tracing information from HTML `<meta>` tags when loading the page.
- Inject tracing information to any outgoing requests.

To learn more about distributed tracing, see our <PlatformLink to="/tracing/trace-propagation/">Distributed Tracing</PlatformLink> docs.

### Extract Tracing Information From HTML `meta` Tags

If you have a server that renders your application's HTML (SSR) and is also running a Sentry SDK, you can connect your backend to your backend via tracing.

To do this, have your server render HTML `<meta>` tags with the Sentry trace information. In your frontend, extract that tracing information when the page is loading and use it to create new transactions connected to that incoming backend trace.

Some Sentry backend SDKs provide a built-in way to inject these `<meta>` tags into rendered HTML. For example:

- [Python](/platforms/python/distributed-tracing/custom-instrumentation/#inject-tracing-information-into-rendered-html)
- [Ruby](/platforms/ruby/distributed-tracing/custom-instrumentation/#inject-tracing-information-into-rendered-html)
- [PHP](/platforms/php/distributed-tracing/custom-instrumentation/#inject-tracing-information-into-rendered-html)

Then, on `pageload` you can do the following:

```javascript
import { propagationContextFromHeaders } from "@sentry/core"; // Before version 8.40.0, import from "@sentry/utils"
import * as Sentry from "@sentry/browser";

// Read meta tag values
const sentryTrace = document.querySelector("meta[name=sentry-trace]")?.content;
const baggage = document.querySelector("meta[name=baggage]")?.content;

// Generate a propagation context from the meta tags
const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
Sentry.getCurrentScope().setPropagationContext(propagationContext);

Sentry.startSpan(
{
name: `Pageload: ${window.location.pathname}`,
op: "pageload",
},
() => {
// do something
}
);
```
In this example, we create a new root span that is attached to the trace specified in the `sentry-trace` and `baggage` HTML `<meta>` tags.
<PlatformCategorySection
supported={["browser"]}
notSupported={["server", "serverless"]}
>
<PlatformContent includePath="distributed-tracing/custom-instrumentation/browser" />
</PlatformCategorySection>

<PlatformCategorySection supported={['server', 'serverless']}>
If you want to use distributed tracing but not tracing, set the `tracesSampleRate` option to `0`.
```javascript
Sentry.init({
dsn: "___PUBLIC_DSN___",

// If this is 0, tracing is disabled
// but distributed tracing is not
tracesSampleRate: 0,
});
```
## Manually Extracting and Injecting Distributed Tracing Information
You can also manually extract and inject tracing data into your application. For this, you must:
- Extract and store incoming tracing information from incoming request headers or similar.
- Inject tracing information to any outgoing requests.
To learn more about distributed tracing, see our <PlatformLink to="/tracing/trace-propagation/">Distributed Tracing</PlatformLink> docs.
### Extracting Incoming Tracing Information
You must extract and store incoming tracing information in memory for later use. Sentry provides the `continueTrace()` function to help you with this. Incoming tracing information can come from different places:
- In a web environment, it's sent with HTTP headers, for example, by another Sentry SDK used in your frontend project.
- In a job queue, it can be retrieved from meta or header variables.
- You also can pick up tracing information from environment variables.
Here's an example of how to extract and store incoming tracing information using `continueTrace()`:
```javascript
const http = require("http");

http.createServer((request, response) => {
const sentryTraceHeaders = request.headers["sentry-trace"];
const sentryTrace = Array.isArray(sentryTraceHeaders)
? sentryTraceHeaders.join(",")
: sentryTraceHeaders;
const baggage = request.headers["baggage"];

Sentry.continueTrace({ sentryTrace, baggage }, () => {
Sentry.startSpan(
{,
name: "my request",
op: "http.server",
},
() => {
// Your API code...
}
);
});
});
```
In this example, we create a new transaction that is attached to the trace specified in the `sentry-trace` and `baggage` headers.
<PlatformCategorySection supported={["server", "serverless"]}>
<PlatformContent includePath="distributed-tracing/custom-instrumentation/server" />
</PlatformCategorySection>

### Inject Tracing Information into Outgoing Requests
Expand All @@ -178,18 +18,9 @@ For distributed tracing to work, the two headers that you extracted and stored i
Here's an example of how to collect and inject this tracing information to outgoing requests:

```javascript
const activeSpan = Sentry.getActiveSpan();
const rootSpan = activeSpan ? Sentry.getRootSpan(activeSpan) : undefined;

// Create `sentry-trace` header
const sentryTraceHeader = rootSpan
? Sentry.spanToTraceHeader(rootSpan)
: undefined;

// Create `baggage` header
const sentryBaggageHeader = rootSpan
? Sentry.spanToBaggageHeader(rootSpan)
: undefined;
const traceData = Sentry.getTraceData();
const sentryTraceHeader = traceData["sentry-trace"];
const sentryBaggageHeader = traceData["baggage"];

// Make outgoing request
fetch("https://example.com", {
Expand All @@ -207,51 +38,6 @@ In this example, tracing information is propagated to the project running at `ht

The two services are now connected with your custom distributed tracing implementation.

<PlatformCategorySection notSupported={['browser']}>

### Injecting Tracing Information into HTML

If you're server-side rendering HTML and you use a Sentry SDK in your browser application, you can connect the backend and frontend traces by injecting your server's tracing information as `<meta>` tags into the HTML that's initially served to the browser. When the frontend SDK is initialized, it will automatically pick up the tracing information from the `<meta>` tags and continue the trace. Note, that your browser SDK needs to register `browserTracingIntegration` for this to work.
The easiest and recommended way to do this is to use the `Sentry.getTraceMetaTags()`:
```javascript {5} {filename:index.js}
function renderHtml() {
return `
<html>
<head>
${Sentry.getTraceMetaTags()}
</head>
<body>
<!-- Your HTML content -->
</body>
</html>
`;
}
```
Alternatively, if you need more control over how meta tags are generated, you can use `Sentry.getTraceData()` to get only the meta tag values and generate the meta tags yourself:
```javascript {2, 7-8} {filename:index.js}
function renderHtml() {
const metaTagValues = Sentry.getTraceData();
return `
<html>
<head>
<meta name="sentry-trace" content="${metaTagValues["sentry-trace"]}">
<meta name="baggage" content="${metaTagValues.baggage}">
</head>
<body>
<!-- Your HTML content -->
</body>
</html>
`;
}
```
</PlatformCategorySection>
### Starting a New Trace

Available since SDK version `8.5.0`.
Expand Down
Loading

0 comments on commit 88da19d

Please sign in to comment.