import { Resource } from '@opentelemetry/resources'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'; import { JaegerExporter, ExporterConfig } from '@opentelemetry/exporter-jaeger'; import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'; import { TracerShim } from '@opentelemetry/shim-opentracing'; import { initGlobalTracer as openTracingInitGlobalTracer } from 'opentracing'; import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; import { ServerResponse } from 'http'; export const createShim = (serviceName: string, config?: ExporterConfig) => { const provider = new NodeTracerProvider({ resource: new Resource({ [SemanticResourceAttributes.SERVICE_NAME]: serviceName, }), }); const exporter = new JaegerExporter(config); provider.addSpanProcessor(new SimpleSpanProcessor(exporter)); if (process.env.ENABLE_HTTP_INSTRUMENTATION) { const expressInstrumentation = new ExpressInstrumentation(); expressInstrumentation.setTracerProvider(provider); const httpInstrumentation = new HttpInstrumentation({ responseHook: (span, response) => { if ((response as ServerResponse).setHeader) { const ctx = span.spanContext(); (response as ServerResponse).setHeader('x-trace-id', ctx.traceId); } }, }); httpInstrumentation.setTracerProvider(provider); } // Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings provider.register(); const tracer = provider.getTracer( process.env.TRACING_SERVICE_NAME || 'tempi-landing', process.env.NEXT_PUBLIC_IMAGE_TAG || '1.0.0', ); return new TracerShim(tracer); }; export const initGlobalTracer = ( serviceName: string, config?: ExporterConfig, ) => { const shim = createShim(serviceName, config); openTracingInitGlobalTracer(shim); };