Integrate OpenTelemetry-JS tracing
Tracing is a mechanism to record paths taken by requests as they propagate through multiple services, for example, from front end app to back-end service to database. Although Faro doesn’t have its own tracing implementation, it can be integrated with OpenTelemetry-JS to capture tracing data, send it to Grafana Cloud and automatically add tracing context to captured logs, exceptions, events, and measurements.
There are two ways to integrate OpenTelemetry-JS tracing with Faro. If you don’t have OpenTelemetry-JS set up in your application, you can use Faro web tracing instrumentation which sets it up for you. If you already have OpenTelemetry-JS, you can configure it to export traces via Faro Web SDK.
Before you begin
Because the OpenTelemetry-JS packages are large, they’re not included in the core or web packages of Grafana Faro Web SDK. You must manually install the Faro tracing package.
Run one of the following commands, depending on your package manager. The command installs the tracing package in your project.
# Using npm
npm install @grafana/faro-web-tracing
# Using yarn
yarn add @grafana/faro-web-tracing
# Using pnpm
pnpm add @grafana/faro-web-tracing
Set up OpenTelemetry-JS tracing via Faro instrumentation
If your application doesn’t have OpenTelemetry-JS, you can use TracingInstrumentation
included with the Faro web tracing package.
The following commands add OpenTelemetry-JS tracing to the list of instrumentations executed when you initialize Faro. These commands initialize OpenTelemetry tracing with document load, fetch, XHR, and user interaction auto-instrumentations.
Note:
To have tracing headers added for CORS requests, you need to define the URLs that should include trace headers.
This is done with the propagateTraceHeaderCorsUrls
property, which is a list of string or Regex patterns.
Integrate existing OpenTelemetry-JS instrumentation with Faro Web SDK
If you already have OpenTelemetry-JS set up in your application, you can integrate it with Faro Web SDK by adding FaroSessionSpanProcessor
to add Faro session id to spans, FaroTraceExporter
to export spans via Faro and registers OpenTelemetry API with the Faro Web SDK instance.
Note:
To add tracing headers for CORS requests, you need to define the URLs that should include the trace headers.
This can be done using the propagateTraceHeaderCorsUrls
property, which is a list of string or Regex patterns.
You can find a complete example here.
Example of starting a trace
The following example shows you how to start a trace.
const { trace, context } = faro.api.getOTEL();
const tracer = trace.getTracer('default');
const span = tracer.startSpan('click');
context.with(trace.setSpan(context.active(), span), () => {
doSomething();
span.end();
});