#Tracing

1 messages · Page 1 of 1 (latest)

clever orbit
#

How can I implement tracing based on OpenTelemetry?

plush valeBOT
#

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:

  1. Enable OpenTelemetry: This feature is experimental in Next.js, so you need to explicitly opt-in by providing experimental.instrumentationHook = true; in your next.config.js file.

  2. 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
  1. Initialize NodeSDK: You can initialize NodeSDK in your instrumentation.ts file. OpenTelemetry APIs are not compatible with edge runtime, so you need to make sure that you are importing them only when process.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')
 }
}
  1. 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()
#
  1. 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.

For more information, you can refer to the Next.js documentation on OpenTelemetry (https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry) and the Official OpenTelemetry docs (https://opentelemetry.io/docs/).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: