|
| 1 | +// This file is built outside of sveltekit and cannot import from the rest of the application |
| 2 | +// or special imports like $env/dynamic/private. |
| 3 | +import { NodeSDK } from "@opentelemetry/sdk-node"; |
| 4 | +import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node"; |
| 5 | +import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics"; |
| 6 | +import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto"; |
| 7 | +import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto"; |
| 8 | +import { SEMRESATTRS_SERVICE_NAME } from "@opentelemetry/semantic-conventions"; |
| 9 | +import { AlwaysOnSampler } from "@opentelemetry/sdk-trace-base"; |
| 10 | +import { Resource } from "@opentelemetry/resources"; |
| 11 | + |
| 12 | +const TRACE_URL = |
| 13 | + process.env.OTEL_EXPORTER_OTLP_ENDPOINT + "/v1/traces" || "http://localhost:4318/v1/traces"; |
| 14 | +const METRICS_URL = |
| 15 | + process.env.OTEL_EXPORTER_OTLP_ENDPOINT + "/v1/metrics" || "http://localhost:4318/v1/metrics"; |
| 16 | +const SERVICE_NAME = process.env.OTEL_SERVICE_NAME || "huggingface/chat-ui"; |
| 17 | + |
| 18 | +const exporter = new OTLPTraceExporter({ |
| 19 | + url: TRACE_URL, |
| 20 | + headers: {}, |
| 21 | +}); |
| 22 | + |
| 23 | +const otelNodeSdk = new NodeSDK({ |
| 24 | + autoDetectResources: true, |
| 25 | + serviceName: SERVICE_NAME, |
| 26 | + traceExporter: exporter, |
| 27 | + metricReader: new PeriodicExportingMetricReader({ |
| 28 | + exporter: new OTLPMetricExporter({ |
| 29 | + url: METRICS_URL, |
| 30 | + headers: {}, |
| 31 | + }), |
| 32 | + }), |
| 33 | + sampler: new AlwaysOnSampler(), |
| 34 | + resource: new Resource({ |
| 35 | + [SEMRESATTRS_SERVICE_NAME]: SERVICE_NAME, |
| 36 | + }), |
| 37 | + instrumentations: [ |
| 38 | + getNodeAutoInstrumentations({ |
| 39 | + "@opentelemetry/instrumentation-http": { |
| 40 | + ignoreIncomingRequestHook: (request) => { |
| 41 | + // Don't trace static asset requests |
| 42 | + if ( |
| 43 | + request.url?.endsWith(".js") || |
| 44 | + request.url?.endsWith(".svg") || |
| 45 | + request.url?.endsWith(".css") |
| 46 | + ) { |
| 47 | + return false; |
| 48 | + } |
| 49 | + return true; |
| 50 | + }, |
| 51 | + }, |
| 52 | + }), |
| 53 | + ], |
| 54 | +}); |
| 55 | + |
| 56 | +export class Telemetry { |
| 57 | + private static instance: Telemetry; |
| 58 | + private initialized = false; |
| 59 | + |
| 60 | + private constructor() {} |
| 61 | + |
| 62 | + public static getInstance(): Telemetry { |
| 63 | + if (!Telemetry.instance) { |
| 64 | + Telemetry.instance = new Telemetry(); |
| 65 | + } |
| 66 | + return Telemetry.instance; |
| 67 | + } |
| 68 | + |
| 69 | + public start() { |
| 70 | + if (!this.initialized) { |
| 71 | + this.initialized = true; |
| 72 | + otelNodeSdk.start(); |
| 73 | + } |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +Telemetry.getInstance().start(); |
0 commit comments