|
| 1 | +export async function register() { |
| 2 | + if (process.env.NEXT_RUNTIME === 'nodejs') { |
| 3 | + const { NodeSDK } = await import('@opentelemetry/sdk-node'); |
| 4 | + const { OTLPTraceExporter } = await import('@opentelemetry/exporter-trace-otlp-http'); |
| 5 | + const { Resource } = await import('@opentelemetry/resources'); |
| 6 | + const { |
| 7 | + ATTR_SERVICE_NAME, |
| 8 | + ATTR_SERVICE_VERSION, |
| 9 | + ATTR_DEPLOYMENT_ENVIRONMENT, |
| 10 | + } = await import('@opentelemetry/semantic-conventions'); |
| 11 | + const { getNodeAutoInstrumentations } = await import('@opentelemetry/auto-instrumentations-node'); |
| 12 | + |
| 13 | + // Only initialize if OTLP endpoint is configured |
| 14 | + const otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT; |
| 15 | + if (!otlpEndpoint) { |
| 16 | + console.log('OpenTelemetry: OTEL_EXPORTER_OTLP_ENDPOINT not set, tracing disabled'); |
| 17 | + return; |
| 18 | + } |
| 19 | + |
| 20 | + const sdk = new NodeSDK({ |
| 21 | + resource: new Resource({ |
| 22 | + [ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || 'manifestsio', |
| 23 | + [ATTR_SERVICE_VERSION]: process.env.OTEL_SERVICE_VERSION || '0.1.0', |
| 24 | + [ATTR_DEPLOYMENT_ENVIRONMENT]: process.env.OTEL_DEPLOYMENT_ENVIRONMENT || 'development', |
| 25 | + }), |
| 26 | + traceExporter: new OTLPTraceExporter({ |
| 27 | + url: `${otlpEndpoint}/v1/traces`, |
| 28 | + headers: process.env.OTEL_EXPORTER_OTLP_HEADERS |
| 29 | + ? Object.fromEntries( |
| 30 | + process.env.OTEL_EXPORTER_OTLP_HEADERS.split(',').map(header => { |
| 31 | + const [key, value] = header.split('='); |
| 32 | + return [key.trim(), value.trim()]; |
| 33 | + }) |
| 34 | + ) |
| 35 | + : {}, |
| 36 | + }), |
| 37 | + instrumentations: [ |
| 38 | + getNodeAutoInstrumentations({ |
| 39 | + // Disable fs instrumentation to reduce noise from Next.js file system operations |
| 40 | + '@opentelemetry/instrumentation-fs': { |
| 41 | + enabled: false, |
| 42 | + }, |
| 43 | + // Configure HTTP instrumentation to capture useful headers |
| 44 | + '@opentelemetry/instrumentation-http': { |
| 45 | + requestHook: (span, request) => { |
| 46 | + span.setAttribute('http.user_agent', request.headers['user-agent'] || 'unknown'); |
| 47 | + }, |
| 48 | + }, |
| 49 | + }), |
| 50 | + ], |
| 51 | + }); |
| 52 | + |
| 53 | + sdk.start(); |
| 54 | + console.log('OpenTelemetry: Tracing initialized successfully'); |
| 55 | + |
| 56 | + // Graceful shutdown |
| 57 | + process.on('SIGTERM', () => { |
| 58 | + sdk |
| 59 | + .shutdown() |
| 60 | + .then(() => console.log('OpenTelemetry: Tracing terminated')) |
| 61 | + .catch(error => console.error('OpenTelemetry: Error terminating tracing', error)) |
| 62 | + .finally(() => process.exit(0)); |
| 63 | + }); |
| 64 | + } |
| 65 | +} |
0 commit comments