Frontend
The frontend is responsible to provide a UI for users, as well as an API leveraged by the UI or other clients. The application is based on Next.JS to provide a React web-based UI and API routes.
Server Instrumentation
It is recommended to use a Node required module when starting your Node.js
application to initialize the SDK and auto-instrumentation. When initializing
the OpenTelemetry Node.js SDK, you optionally specify which auto-instrumentation
libraries to leverage, or make use of the getNodeAutoInstrumentations()
function which includes most popular frameworks. The
utils/telemetry/Instrumentation.js file contains all code required to
initialize the SDK and auto-instrumentation based on standard
OpenTelemetry environment variables
for OTLP export, resource attributes, and service name.
const { NodeSDK } = require('@opentelemetry/sdk-node');
const {
BaggageSpanProcessor,
} = require('@opentelemetry/baggage-span-processor');
// ... other require() calls elided for brevity.
const BAGGAGE_SPAN_ATTRIBUTES = ['session.id', 'enduser.id'];
const sdk = new NodeSDK({
instrumentations: getNodeAutoInstrumentations(),
spanProcessors: [
new BaggageSpanProcessor((key) => BAGGAGE_SPAN_ATTRIBUTES.includes(key)),
new BatchSpanProcessor({ exporter: new OTLPTraceExporter() }),
],
logRecordProcessors: [
new BatchLogRecordProcessor({ exporter: new OTLPLogExporter() }),
],
metricReaders: [
new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter() }),
],
resourceDetectors: [
containerDetector,
envDetector,
hostDetector,
osDetector,
processDetector,
alibabaCloudEcsDetector,
awsEksDetector,
awsEc2Detector,
gcpDetector,
],
});
sdk.start();
The BaggageSpanProcessor copies the session.id and enduser.id baggage
entries sent by the browser onto every server span. This way, the server spans
of a request carry the same session as the browser span that started it.
Node required modules are loaded using the --require command line argument.
This can be done in the scripts.start section of package.json and starting
the application using npm start.
"scripts": {
"start": "node --require ./Instrumentation.js server.js",
},
Traces
Span Exceptions and status
You can use the span object’s recordException function to create a span event
with the full stack trace of a handled error. When recording an exception also
be sure to set the span’s status accordingly. You can see this in the catch
block of the NextApiHandler function in the
utils/telemetry/InstrumentationMiddleware.ts file.
span.recordException(error as Exception);
span.setStatus({ code: SpanStatusCode.ERROR });
Create new spans
New spans can be created and started using
Tracer.startSpan("spanName", options). Several options can be used to specify
how the span can be created.
root: truewill create a new trace, setting this span as the root.linksare used to specify links to other spans (even within another trace) that should be referenced.attributesare key/value pairs added to a span, typically used for application context.
span = tracer.startSpan(`${method}`, {
root: true,
kind: SpanKind.SERVER,
links: [{ context: syntheticSpan.spanContext() }],
attributes: {
'demo.synthetic_request': true,
[ATTR_HTTP_RESPONSE_STATUS_CODE]: response.statusCode,
[ATTR_HTTP_REQUEST_METHOD]: method,
[ATTR_USER_AGENT_ORIGINAL]: headers['user-agent'] || '',
[ATTR_URL_PATH]: target,
[ATTR_URL_FULL]: `${headers.host}${url}`,
[ATTR_NETWORK_PROTOCOL_VERSION]: httpVersion,
},
});
Browser Instrumentation
The web-based UI that the frontend provides is also instrumented for web
browsers. OpenTelemetry instrumentation is included as part of the Next.js App
component in pages/_app.tsx. Here instrumentation is imported and initialized.
import FrontendTracer from '../utils/telemetry/FrontendTracer';
if (typeof window !== 'undefined') FrontendTracer();
The utils/telemetry/FrontendTracer.ts file initializes the
OpenTelemetry browser SDK
using startBrowserSdk from @opentelemetry/browser-sdk. The browser SDK owns
the tracer and logger providers, the propagators, the context manager, and the
OTLP/HTTP batch processors, so none of these need to be assembled by hand.
Instrumentations come from the @opentelemetry/browser-instrumentation package.
The browser emits:
- Spans for fetch, XHR, and document load.
- Events (exported as OTLP logs) for user actions such as clicks, web vitals, errors, console messages, navigation, and resource, navigation, element, and long animation frame timings.
Spans are exported to NEXT_PUBLIC_OTEL_EXPORTER_OTLP_TRACES_ENDPOINT and
events to NEXT_PUBLIC_OTEL_EXPORTER_OTLP_LOGS_ENDPOINT. Both are populated
from the PUBLIC_OTEL_EXPORTER_OTLP_TRACES_ENDPOINT and
PUBLIC_OTEL_EXPORTER_OTLP_LOGS_ENDPOINT environment variables, which point to
the /otlp-http route of the frontend-proxy that forwards to the OpenTelemetry
Collector. Both export URLs are ignored by the fetch, XHR, and resource timing
instrumentations, so the SDK doesn’t trace its own exports.
Each span and log record is enriched by processors that add:
session.id, from the browser SDK session manager.- Document attributes, such as the current page URL.
enduser.id, the demo session user ID, through theEnduserIdProcessorandEnduserIdLogRecordProcessor.
To carry over the synthetic_request attribute flag for the backend services,
the applyCustomAttributesOnSpan configuration function is set on the fetch and
XHR instrumentations, so that every browser-side request span includes it.
import { ConsoleInstrumentation } from '@opentelemetry/browser-instrumentation/experimental/console';
import { DocumentLoadInstrumentation } from '@opentelemetry/browser-instrumentation/experimental/document-load';
import { FetchInstrumentation } from '@opentelemetry/browser-instrumentation/experimental/fetch';
import { XhrInstrumentation } from '@opentelemetry/browser-instrumentation/experimental/xhr';
// ... other instrumentation imports elided for brevity.
import { startBrowserSdk } from '@opentelemetry/browser-sdk';
import { browserDetector } from '@opentelemetry/browser-sdk/browser-detector';
import {
createDocumentLogRecordProcessor,
createDocumentSpanProcessor,
createLocationDocumentProvider,
} from '@opentelemetry/browser-sdk/document';
import {
createSessionLogRecordProcessor,
createSessionSpanProcessor,
} from '@opentelemetry/browser-sdk/session';
import { sessionManager } from './BrowserSession';
import { EnduserIdLogRecordProcessor } from './EnduserIdLogRecordProcessor';
import { EnduserIdProcessor } from './EnduserIdProcessor';
const {
NEXT_PUBLIC_OTEL_SERVICE_NAME = '',
NEXT_PUBLIC_OTEL_EXPORTER_OTLP_TRACES_ENDPOINT = '',
NEXT_PUBLIC_OTEL_EXPORTER_OTLP_LOGS_ENDPOINT = '',
IS_SYNTHETIC_REQUEST = '',
} = typeof window !== 'undefined' ? window.ENV : {};
const tracesUrl =
NEXT_PUBLIC_OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ||
'http://localhost:4318/v1/traces';
const logsUrl =
NEXT_PUBLIC_OTEL_EXPORTER_OTLP_LOGS_ENDPOINT ||
'http://localhost:4318/v1/logs';
const exportUrls = [tracesUrl, logsUrl];
const batchProcessorConfig = { scheduledDelayMillis: 500 };
const FrontendTracer = async () => {
await sessionManager.start();
const documentProvider = createLocationDocumentProvider();
const sdk = startBrowserSdk({
serviceName: NEXT_PUBLIC_OTEL_SERVICE_NAME,
resourceAttributes: browserDetector.detect().attributes,
traces: {
processors: [
createSessionSpanProcessor(sessionManager),
createDocumentSpanProcessor(documentProvider),
new EnduserIdProcessor(),
],
exportConfig: { url: tracesUrl },
batchProcessorConfig,
},
logs: {
processors: [
createSessionLogRecordProcessor(sessionManager),
createDocumentLogRecordProcessor(documentProvider),
new EnduserIdLogRecordProcessor(),
],
exportConfig: { url: logsUrl },
batchProcessorConfig,
},
instrumentations: [
new ConsoleInstrumentation(),
new DocumentLoadInstrumentation(),
// ... other event instrumentations elided for brevity.
new FetchInstrumentation({
propagateTraceHeaderCorsUrls: [/.*/],
ignoreUrls: exportUrls,
applyCustomAttributesOnSpan(span) {
span.setAttribute('demo.synthetic_request', IS_SYNTHETIC_REQUEST);
},
}),
new XhrInstrumentation({
propagateTraceHeaderCorsUrls: [/.*/],
ignoreUrls: exportUrls,
applyCustomAttributesOnSpan(span) {
span.setAttribute('demo.synthetic_request', IS_SYNTHETIC_REQUEST);
},
}),
],
});
if (sdk.invalidConfig) {
throw new Error(
'Browser SDK failed to start due to an invalid configuration',
);
}
};
export default FrontendTracer;
Browser sessions
The utils/telemetry/BrowserSession.ts file creates the session manager used by
the browser SDK. The session ID is persisted in local storage and is rotated
after 30 minutes of inactivity, or after a maximum duration of 4 hours.
import {
createDefaultSessionIdGenerator,
createLocalStorageSessionStore,
createSessionManager,
} from '@opentelemetry/browser-sdk/session';
export const sessionManager = createSessionManager({
sessionIdGenerator: createDefaultSessionIdGenerator(),
sessionStore: createLocalStorageSessionStore(),
maxDuration: 4 * 60 * 60,
inactivityTimeout: 30 * 60,
});
Metrics
TBD
Logs
The browser events emitted by the browser SDK carry an event name and attributes
only, without a body or severity text. To keep them readable in the logs UI, the
OpenTelemetry Collector uses a transform/browser_events processor in the logs
pipeline to set the log body from the event name and to derive the severity text
from the severity number.
Baggage
OpenTelemetry Baggage is leveraged in the frontend to check if the request is synthetic (from the load generator). Synthetic requests will force the creation of a new trace. The root span from the new trace will contain many of the same attributes as an HTTP request instrumented span.
To determine if a Baggage item is set, you can leverage the propagation API to
parse the Baggage header, and leverage the baggage API to get or set entries.
const baggage = propagation.getBaggage(context.active());
if (baggage?.getEntry("synthetic_request")?.value == "true") {...}
Baggage is also used to propagate the browser session to the backend. Before
each API call, gateways/Api.gateway.ts sets the session.id entry from the
browser SDK session manager and the enduser.id entry from the demo session
user ID. On the server, the BaggageSpanProcessor copies both entries onto the
server spans, as described in Server Instrumentation.
const baggage = propagation.getActiveBaggage() || propagation.createBaggage();
const sessionId = sessionManager.getSessionId();
let newBaggage = baggage.setEntry(AttributeNames.ENDUSER_ID, { value: userId });
if (sessionId) {
newBaggage = newBaggage.setEntry(AttributeNames.SESSION_ID, {
value: sessionId,
});
}
const newContext = propagation.setBaggage(context.active(), newBaggage);
Feedback
Was this page helpful?
Thank you. Your feedback is appreciated!
Please let us know how we can improve this page. Your feedback is appreciated!