This page explains how to send traces, metrics, and logs from a Hono app running on Node.js, Bun, or Cloudflare Workers to Axiom.
Hono is a lightweight web framework built on Web Standards that runs on many JavaScript runtimes, including Node.js, Bun, and Cloudflare Workers.
This page explains how to send the following data from a Hono app to Axiom:
Traces: The @hono/otel middleware creates an OpenTelemetry span for every request. An OpenTelemetry SDK exports the spans to Axiom over OTLP/HTTP.
Metrics: On Node.js and Bun, @hono/otel also records the http.server.request.duration and http.server.active_requests metrics, and the OpenTelemetry SDK exports them to Axiom.
Logs: The @axiomhq/logging library sends structured logs to Axiom. Each log contains the trace ID and span ID of the request that produced it.
The OpenTelemetry Node.js SDK doesn’t run on Cloudflare Workers, and @microlabs/otel-cf-workers only exports traces. For more information, see Usage on Cloudflare Workers in the @hono/otel documentation.
Create datasets for traces, logs, and metrics. Recommended: Create the datasets in a correlation group. To create all three at once, go to Datasets > Correlations > New correlation group, select From new datasets, and enter a prefix such as hono. Axiom creates hono-traces, hono-logs, and hono-metrics. If you only use Cloudflare Workers, you don’t need the metrics dataset.
The OpenTelemetry exporters send data to the OTLP/HTTP endpoints of your Axiom edge deployment. Axiom doesn’t support OTLP over gRPC.
Signal
Endpoint
Dataset header
Traces
https://AXIOM_DOMAIN/v1/traces
X-Axiom-Dataset
Metrics
https://AXIOM_DOMAIN/v1/metrics
X-Axiom-Metrics-Dataset
Each request also contains the Authorization: Bearer API_TOKEN header.
The @axiomhq/logging library sends logs through the @axiomhq/js client to the ingest endpoint of the same edge deployment. To select the edge deployment, set the edge option of the client to the base domain of the edge deployment.
Replace AXIOM_DOMAIN with the base domain of your edge deployment. For more information, see Edge deployments.
The -proto exporters send data encoded as Protobuf (http/protobuf). To send JSON instead, use @opentelemetry/exporter-trace-otlp-http and @opentelemetry/exporter-metrics-otlp-http.
Create the file src/instrumentation.ts. It starts the OpenTelemetry Node.js SDK, which exports spans to the traces dataset and metrics to the metrics dataset.
typescript
import { NodeSDK } from '@opentelemetry/sdk-node';import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto';import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';import { resourceFromAttributes } from '@opentelemetry/resources';import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';const endpoint = `https://${process.env.AXIOM_DOMAIN}`;const authorization = `Bearer ${process.env.AXIOM_TOKEN}`;export const sdk = new NodeSDK({ resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: 'hono-app', }), // Send spans to the traces dataset traceExporter: new OTLPTraceExporter({ url: `${endpoint}/v1/traces`, headers: { Authorization: authorization, 'X-Axiom-Dataset': process.env.AXIOM_TRACES_DATASET!, }, }), // Send request metrics to the metrics dataset metricReaders: [ new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter({ url: `${endpoint}/v1/metrics`, headers: { Authorization: authorization, 'X-Axiom-Metrics-Dataset': process.env.AXIOM_METRICS_DATASET!, }, }), }), ],});sdk.start();
Update the entry point of your app. The example below does the following:
Imports src/instrumentation.ts before anything else, so the SDK is ready when the first request arrives.
Adds the httpInstrumentationMiddleware middleware of @hono/otel, which creates a span for every request. The span name contains the method and the route pattern, for example GET /users/:id. If the response status is 500 or higher, the span status is ERROR, and unhandled errors are recorded as exceptions on the span.
Adds a middleware that creates a child logger with the trace_id and span_id of the current span, and stores it in the context. Every log that a route handler sends with this logger contains these fields.
Sends the buffered logs and spans to Axiom when the process receives the SIGTERM signal.
typescript
import { sdk } from './instrumentation.js';import { serve } from '@hono/node-server';import { httpInstrumentationMiddleware } from '@hono/otel';import { trace } from '@opentelemetry/api';import { Hono } from 'hono';import type { Logger } from '@axiomhq/logging';import { logger } from './logger.js';const app = new Hono<{ Variables: { logger: Logger } }>();// Create a span for every requestapp.use(httpInstrumentationMiddleware());// Add the trace context to the logs of every requestapp.use(async (c, next) => { const spanContext = trace.getActiveSpan()?.spanContext(); c.set('logger', logger.with({ trace_id: spanContext?.traceId, span_id: spanContext?.spanId, })); await next();});app.get('/', (c) => { c.get('logger').info('Handled request', { path: c.req.path }); return c.text('Hello Hono!');});app.get('/users/:id', (c) => { c.get('logger').info('Fetched user', { userId: c.req.param('id') }); return c.json({ id: c.req.param('id') });});app.get('/error', () => { throw new Error('Something went wrong');});app.onError((err, c) => { c.get('logger').error('Unhandled error', err); return c.text('Internal Server Error', 500);});serve({ fetch: app.fetch, port: 3000 });// Send buffered logs and spans before the process exitsprocess.on('SIGTERM', async () => { await Promise.all([logger.flush(), sdk.shutdown()]); process.exit(0);});
typescript
import { sdk } from './instrumentation';import { httpInstrumentationMiddleware } from '@hono/otel';import { trace } from '@opentelemetry/api';import { Hono } from 'hono';import type { Logger } from '@axiomhq/logging';import { logger } from './logger';const app = new Hono<{ Variables: { logger: Logger } }>();// Create a span for every requestapp.use(httpInstrumentationMiddleware());// Add the trace context to the logs of every requestapp.use(async (c, next) => { const spanContext = trace.getActiveSpan()?.spanContext(); c.set('logger', logger.with({ trace_id: spanContext?.traceId, span_id: spanContext?.spanId, })); await next();});app.get('/', (c) => { c.get('logger').info('Handled request', { path: c.req.path }); return c.text('Hello Hono!');});app.get('/users/:id', (c) => { c.get('logger').info('Fetched user', { userId: c.req.param('id') }); return c.json({ id: c.req.param('id') });});app.get('/error', () => { throw new Error('Something went wrong');});app.onError((err, c) => { c.get('logger').error('Unhandled error', err); return c.text('Internal Server Error', 500);});// Send buffered logs and spans before the process exitsprocess.on('SIGTERM', async () => { await Promise.all([logger.flush(), sdk.shutdown()]); process.exit(0);});export default app;
@hono/otel instruments the request-response lifecycle as a whole and doesn’t create spans for individual middleware. To trace outgoing HTTP requests and database calls on Node.js, add OpenTelemetry instrumentations to the SDK. For more information, see OpenTelemetry using Node.js.
On Cloudflare Workers, the instrument function of @microlabs/otel-cf-workers sets up OpenTelemetry for the Worker and exports spans to Axiom. It creates a span for every invocation and automatically traces outgoing fetch calls. The @hono/otel middleware adds a child span that contains the Hono route.
In your Wrangler configuration file, turn on the nodejs_compat compatibility flag, which @microlabs/otel-cf-workers requires, and add the Axiom settings as environment variables:
Store the API token as a secret, not as an environment variable in the Wrangler configuration file. For local development, create a .dev.vars file in the root folder of your app:
shell
AXIOM_TOKEN=API_TOKEN
For the deployed Worker, run the following command, and then enter the API token:
shell
npx wrangler secret put AXIOM_TOKEN
For more information, see Secrets in the Cloudflare documentation.
Update src/index.ts. The example below does the following:
Adds the httpInstrumentationMiddleware middleware of @hono/otel, which creates a span for every request.
Adds a middleware that creates a logger for every request. The environment variables of a Worker are only available while it handles a request, so the logger can’t be created when the module loads. The logger adds the trace_id and span_id of the current span to every log.
Sends the logs of the request to Axiom with c.executionCtx.waitUntil, which keeps the Worker running after it sends the response until the logs are delivered. For more information, see executionCtx in the Hono documentation.
Wraps the app with the instrument function, which exports the spans to the traces dataset.
typescript
import { Axiom } from '@axiomhq/js';import { AxiomJSTransport, ConsoleTransport, Logger } from '@axiomhq/logging';import { httpInstrumentationMiddleware } from '@hono/otel';import { instrument, type ResolveConfigFn } from '@microlabs/otel-cf-workers';import { trace } from '@opentelemetry/api';import { Hono } from 'hono';type Bindings = { AXIOM_DOMAIN: string; AXIOM_TOKEN: string; AXIOM_TRACES_DATASET: string; AXIOM_LOGS_DATASET: string;};const app = new Hono<{ Bindings: Bindings; Variables: { logger: Logger } }>();// Create a span for every requestapp.use(httpInstrumentationMiddleware());// Create a logger for every request and send its logs after the responseapp.use(async (c, next) => { const axiom = new Axiom({ token: c.env.AXIOM_TOKEN, edge: c.env.AXIOM_DOMAIN }); const spanContext = trace.getActiveSpan()?.spanContext(); const logger = new Logger({ transports: [ new AxiomJSTransport({ axiom, dataset: c.env.AXIOM_LOGS_DATASET }), new ConsoleTransport(), ], args: { trace_id: spanContext?.traceId, span_id: spanContext?.spanId, }, }); c.set('logger', logger); try { await next(); } finally { c.executionCtx.waitUntil(logger.flush()); }});app.get('/', (c) => { c.get('logger').info('Handled request', { path: c.req.path }); return c.text('Hello Hono!');});app.get('/users/:id', (c) => { c.get('logger').info('Fetched user', { userId: c.req.param('id') }); return c.json({ id: c.req.param('id') });});app.get('/error', () => { throw new Error('Something went wrong');});app.onError((err, c) => { c.get('logger').error('Unhandled error', err); return c.text('Internal Server Error', 500);});// Send spans to the traces datasetconst config: ResolveConfigFn<Bindings> = (env) => ({ exporter: { url: `https://${env.AXIOM_DOMAIN}/v1/traces`, headers: { Authorization: `Bearer ${env.AXIOM_TOKEN}`, 'X-Axiom-Dataset': env.AXIOM_TRACES_DATASET, }, }, service: { name: 'hono-worker' },});export default instrument(app, config);
Replace hono-worker with the name of your service.
Each request produces the following spans in the same trace:
fetchHandler GET: The span that @microlabs/otel-cf-workers creates for the invocation.
A span with the method and the route pattern, for example GET /users/:id: The span that @hono/otel creates.
fetch POST AXIOM_DOMAIN: The outgoing request that sends the logs of the request to Axiom.
The Workers runtime only advances the clock during I/O, so the duration of CPU-bound work appears as zero. For more information, see Limitations in the @microlabs/otel-cf-workers documentation.
To compute the 90th and 99th percentiles of the request duration for each route, run the following MPL query:
MPL
`METRICS_DATASET_NAME`:`http.server.request.duration`| where `http.response.status_code` < 400| bucket by `http.request.method`, `http.route` to 5m using interpolate_cumulative_histogram(rate, 0.90, 0.99)
The query computes a rate from consecutive exports, so it returns results after the SDK has exported metrics at least twice. With the default export interval, this takes about two minutes of traffic.