@crossdelta/telemetry
v0.19.0
Published
OpenTelemetry instrumentation for CrossDelta services
Maintainers
Readme
@crossdelta/telemetry
OpenTelemetry instrumentation for TypeScript services on Bun and Node.js.
Getting Started
1. Install
bun add @crossdelta/telemetry2. Import (first line!)
import '@crossdelta/telemetry'
import { Hono } from 'hono'The import must come before everything else to properly patch modules.
3. Set environment variables
OTEL_SERVICE_NAME=my-service
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://otlp-gateway.grafana.net/otlp/v1/traces
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://otlp-gateway.grafana.net/otlp/v1/logs
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://otlp-gateway.grafana.net/otlp/v1/metrics
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic base64(instanceId:apiKey)If no endpoint is configured, telemetry stays disabled with zero overhead.
4. Flush on shutdown
The package registers no signal listener: one would replace the default "terminate" of SIGTERM and
keep the process running until SIGKILL. The service calls shutdownTelemetry() as the last step
of its own shutdown, after its server and consumers have finished, and exits the process itself:
import { shutdownTelemetry } from '@crossdelta/telemetry'
process.once('SIGTERM', async () => {
await server.stop()
await shutdownTelemetry() // flushes spans, logs and metrics; never throws
process.exit(0)
})Usage
Hono services (Bun)
Wire instrumentMiddleware() to get per-request spans, HTTP metrics, and log context. Every console.* call within a request automatically includes requestId, traceId, path, and method in Grafana.
import '@crossdelta/telemetry'
import { instrumentMiddleware } from '@crossdelta/telemetry/middleware'
import { Hono } from 'hono'
const app = new Hono()
app.use('*', instrumentMiddleware())Per request this creates:
- An OTEL server span (
http.method,http.target,http.status_code,http.route) - An
http.server.request.durationhistogram entry withhttp.request.method,http.response.status_codeandhttp.route - ALS context with
requestId,traceId,spanId,path,methodfor log correlation
http.route is the template of the route that answered (/orders/:id), never the raw path, so it adds one series per route and not one per ID; the span is then named <method> <template>. A request no route answered (a 404 from the not-found handler) carries no http.route, and neither does a Hono route registered with all() or an Express route under a mounted router (its prefix is the path as the request spelled it). http.request.method on the histogram is a known HTTP method or _OTHER.
Request metric options (Bun adapters)
| Variable | Default | Effect |
| --- | --- | --- |
| TELEMETRY_UNMEASURED_ROUTES | /health,/health/ready | Comma-separated route templates that keep their span but record no http.server.request.duration, so liveness and readiness probes do not dilute rates, error shares and percentiles. Compared exactly with the route template, or with the path when no route matched. An empty value measures every route |
| TELEMETRY_HTTP_DURATION_BUCKETS | unset: the SDK's default buckets | Comma-separated, strictly ascending upper bounds in milliseconds for the histogram, e.g. 25,50,100,200,300,500,1000,2500,5000. Fewer buckets mean fewer series per route; put a bound at your latency target to read it exactly. An invalid value logs a warning and keeps the default |
Outgoing calls
With a metrics endpoint and TELEMETRY_CLIENT_HOSTS set, the package replaces globalThis.fetch at import time and records http.client.request.duration for every call to a listed host, from the call until the response headers arrive. Attributes: server.address (the host) and, on a failure, error.type (5xx for any answer from 500 up, or TimeoutError, AbortError, TypeError, otherwise _OTHER). A 4xx answer counts as an answer. Method and status code are left out, so a host adds one series per bucket and failure kind. Calls to other hosts, and clients that do not use fetch (axios, node:http), are not measured.
| Variable | Default | Effect |
| --- | --- | --- |
| TELEMETRY_CLIENT_HOSTS | unset: no outgoing call is measured | Comma-separated hosts; an entry with a leading dot (.example.com) matches every host below that domain, any other entry exactly one host. Only listed hosts reach server.address |
The histogram uses the bounds of TELEMETRY_HTTP_DURATION_BUCKETS.
The W3C traceparent header is propagated automatically, so all downstream services share the same traceId. NATS CloudEvents carry trace context via @crossdelta/cloudevents.
On Node.js (NestJS/Express), HttpInstrumentation handles spans and metrics automatically. instrumentMiddleware() only sets up the ALS context there.
Express and NestJS on Bun
On Node.js the HTTP, Express and Pino instrumentations register themselves. On Bun they do not, so an Express or NestJS (Express platform) service gets neither spans, request metrics nor exported logs without the adapters from @crossdelta/telemetry/express:
import '@crossdelta/telemetry'
import { instrumentExpress, isBunRuntime, withOtelLogStream } from '@crossdelta/telemetry/express'
import { NestFactory } from '@nestjs/core'
import { LoggerModule } from 'nestjs-pino'
const app = await NestFactory.create(AppModule)
app.use(instrumentExpress()) // first in the chain
// in the module: nestjs-pino writes to stdout and, through the stream, to the OTEL log pipeline
LoggerModule.forRoot({ pinoHttp: withOtelLogStream({ level: 'info' }, isBunRuntime()) })instrumentExpress() creates the same server span and http.server.request.duration histogram as instrumentMiddleware(), with http.route from the router prefix and the matched route path and the same request metric options, continues an incoming traceparent, and keeps the span active for the rest of the request. On Node.js it only sets up the ALS context and the X-Request-Id header. withOtelLogStream(options, active) returns [options, stream] for pino and nestjs-pino; pino accepts a stream or a transport, not both, so pass active false where a transport (for example pino-pretty) is configured.
Logging
For most cases, plain console.* works. The OTEL patch captures everything and attaches trace context automatically.
console.info('[ORDER:CREATED]', orderId)
console.error('[PAYMENT:FAILED]', reason)For queryable key-value attributes in Grafana:
import { logInfo, logError } from '@crossdelta/telemetry/logger'
await logInfo('Order created', { orderId, total, tenantId })
await logError('Payment failed', { orderId, reason, provider })Qwik apps
import { initRequestContext } from '@crossdelta/telemetry/logger'
export const onRequest: RequestHandler = async (ev) => {
const requestId = initRequestContext(ev)
ev.headers.set('X-Request-Id', requestId)
}Custom initialization
For non-default settings, use initTelemetry() instead of the side-effect import:
import { initTelemetry } from '@crossdelta/telemetry'
initTelemetry({
metricsIntervalMs: 30_000,
onShutdown: async () => {
await database.close()
},
})Runtime Support
All signals (logs, metrics, traces) work on both runtimes. The difference is how HTTP spans and metrics are created:
| Feature | Node.js | Bun |
|---------|---------|-----|
| HTTP spans | auto (HttpInstrumentation) | instrumentMiddleware() |
| HTTP metrics | auto (HttpInstrumentation, metric http.server.duration) | instrumentMiddleware() / instrumentExpress() (metric http.server.request.duration, in ms) |
| Express/NestJS spans and metrics | auto (HttpInstrumentation, ExpressInstrumentation) | instrumentExpress() |
| pino logs to OTEL | auto (PinoInstrumentation) | withOtelLogStream() |
Process Metrics
With OTEL_EXPORTER_OTLP_METRICS_ENDPOINT set, every process reports four gauges on Bun and Node.js, without any code in the service. Each carries process.runtime.name (bun or nodejs):
| Metric | Unit | Value |
|--------|------|-------|
| process.memory.usage | By | Resident set size |
| process.memory.heap.used | By | Used JavaScript heap |
| process.memory.heap.total | By | Allocated JavaScript heap |
| process.uptime | s | Seconds since the process started; a drop means a restart |
So that replicas of a service do not overwrite each other's series, the resource gets a service.instance.id: HOSTNAME (the pod name in Kubernetes), else a random UUID. A value set through OTEL_RESOURCE_ATTRIBUTES is kept.
Supported Backends
Grafana Cloud, Better Stack, Jaeger — any OTLP endpoint works.
API Reference
Essential
| Export | From | Description |
|--------|------|-------------|
| import '@crossdelta/telemetry' | . | Auto-initialize SDK (side-effect import) |
| instrumentMiddleware() | ./middleware | Hono middleware: server span, HTTP metrics, ALS context, X-Request-Id header |
| instrumentExpress() | ./express | Express/NestJS middleware: the same span and metric as the Hono middleware, on Bun |
| instrumentFetch(handler, routeOf) | ./serve | Wraps a plain Bun.serve fetch handler: the same span and metric, ALS context; routeOf(url) names http.route from a fixed set, never the raw path |
| withOtelLogStream(options, active) | ./express | pino/nestjs-pino option: stdout plus a copy to the OTEL log pipeline |
| logInfo(msg, data?) | ./logger | Structured info log with ALS context |
| logWarn(msg, data?) | ./logger | Structured warning log with ALS context |
| logError(msg, data?) | ./logger | Structured error log with ALS context |
| logDebug(msg, data?) | ./logger | Structured debug log with ALS context |
| initRequestContext(event) | ./logger | Set up per-request ALS context. Returns requestId. |
| logger | ./logger | Universal logger object (server: Pino+ALS, client: console) |
Advanced
| Export | From | Description |
|--------|------|-------------|
| initTelemetry(config?) | . | Manual SDK initialization with custom options |
| shutdownTelemetry() | . | Flush pending data and shut down the SDK; the last step of the service's own shutdown, never throws |
| getSDK() | . | Get the current NodeSDK instance (or null) |
| extractTraceparent(request) | ./traceparent | Parse W3C traceparent header from a Request |
| parseTraceparent(header) | ./traceparent | Parse a W3C traceparent string |
| buildTraceparent(context) | ./traceparent | Build a W3C traceparent header from trace context |
| getCurrentTraceparent() | ./traceparent | Get current traceparent from ALS or OTEL active span |
| runWithTraceparent(header, fn) | ./traceparent | Run a function inside a trace context derived from a traceparent header |
| createOtelLogStream(options?) | ./express | The pino destination stream behind withOtelLogStream |
| isBunRuntime() | ./express | True on Bun |
| runWithLogContext(context, fn) | ./logger | Run a function inside a custom ALS context |
| buildRequestLogContext(req, url) | ./logger | Build a LogContext Map from a Request |
| getLogContext() | ./logger | Read current ALS context as a plain object |
| withLogging(name, fn, opts?) | ./logger | Wrap async function with auto error + slow-call logging |
| serializeError(error) | ./logger | Serialize Error to { err, errName, stack, cause } |
In production, set OTEL_* vars via your secrets manager or CI/CD.
License
MIT
