#Tracing
1 messages · Page 1 of 1 (latest)
Hi @clever orbit. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To implement tracing based on OpenTelemetry in your Next.js application, you can follow these steps:
-
Enable OpenTelemetry: This feature is experimental in Next.js, so you need to explicitly opt-in by providing
experimental.instrumentationHook = true;in yournext.config.jsfile. -
Install OpenTelemetry packages: You can install the necessary OpenTelemetry packages using npm. Here's the command you need to run in your terminal:
npm install @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
- Initialize NodeSDK: You can initialize
NodeSDKin yourinstrumentation.tsfile. OpenTelemetry APIs are not compatible with edge runtime, so you need to make sure that you are importing them only whenprocess.env.NEXT_RUNTIME === 'nodejs'. Here's an example of how you can do this:
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
await import('./instrumentation.node.ts')
}
}
- Create a new file
instrumentation.node.ts: This file should be conditionally imported only when using node. Here's an example of what this file could look like:
import { NodeSDK } from '@opentelemetry/sdk-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { Resource } from '@opentelemetry/resources'
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node'
const sdk = new NodeSDK({
resource: new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: 'next-app',
}),
spanProcessor: new SimpleSpanProcessor(new OTLPTraceExporter()),
})
sdk.start()
- Add custom spans: You can add custom spans with OpenTelemetry APIs. Here's an example of how you can do this:
import { trace } from '@opentelemetry/api'
export async function fetchGithubStars() {
return await trace
.getTracer('nextjs-example')
.startActiveSpan('fetchGithubStars', async (span) => {
try {
return await getValue()
} finally {
span.end()
}
})
}
Please note that this is equivalent to using @vercel/otel, but it's possible to modify and extend. For example, you could use @opentelemetry/exporter-trace-otlp-grpc instead of @opentelemetry/exporter-trace-otlp-http or you can specify more resource attributes.