-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathinstrumentation.ts
More file actions
52 lines (45 loc) · 2.19 KB
/
Copy pathinstrumentation.ts
File metadata and controls
52 lines (45 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* OpenTelemetry instrumentation — loaded before the app via the --import flag.
*
* Registered instrumentations:
* - HTTP — inbound/outbound HTTP request spans
* - @fastify/otel — Fastify route + lifecycle hook spans (official Fastify plugin)
*
* CQRS tracing is handled by application-level middleware that uses
* @opentelemetry/api directly (see src/shared/cqrs/otel-middleware.ts).
*
* Controlled entirely by standard OpenTelemetry environment variables:
* OTEL_SDK_DISABLED — set to "true" to disable (default in .env.example)
* OTEL_SERVICE_NAME — logical service name (e.g. "fastify-boilerplate")
* OTEL_EXPORTER_OTLP_ENDPOINT — collector URL (e.g. http://localhost:4318)
* OTEL_TRACES_EXPORTER — trace exporter (default: "otlp")
* OTEL_METRICS_EXPORTER — metrics exporter (default: "otlp")
* OTEL_LOGS_EXPORTER — logs exporter (default: "otlp")
*
* Full reference:
* https://opentelemetry.io/docs/languages/sdk-configuration/general/
*/
import type { NodeSDK } from '@opentelemetry/sdk-node';
let sdk: NodeSDK | undefined;
if (process.env.OTEL_SDK_DISABLED !== 'true') {
// Register the ESM loader hook so OpenTelemetry can patch imported modules
// (http, etc.). Must be called before any application imports.
const { register } = await import('node:module');
register('@opentelemetry/instrumentation/hook.mjs', import.meta.url);
const { NodeSDK } = await import('@opentelemetry/sdk-node');
const { HttpInstrumentation } = await import('@opentelemetry/instrumentation-http');
const { FastifyOtelInstrumentation } = await import('@fastify/otel');
sdk = new NodeSDK({
instrumentations: [
new HttpInstrumentation(),
// registerOnInitialization auto-registers the Fastify plugin on server creation
new FastifyOtelInstrumentation({ registerOnInitialization: true }),
],
});
sdk.start();
}
/** Flushes and shuts down the OpenTelemetry SDK so buffered spans/metrics are exported
* before the process exits. No-op when telemetry is disabled. Call from graceful shutdown. */
export async function shutdownTelemetry(): Promise<void> {
await sdk?.shutdown();
}