Express Logging and Tracing in Node.js: What OpenTelemetry Really Costs
Tutorials nodejs express observability opentelemetry logging

Express Logging and Tracing in Node.js: What OpenTelemetry Really Costs

D. Rout

D. Rout

November 30, 2026 24 min read

On this page

A production request fails, and you have a thousand log lines from fifty concurrent requests with no way to tell them apart. Or you add tracing, the dashboard stays half empty, and nothing throws an error. Observability for Node/Express services is easy to switch on and surprisingly easy to get quietly wrong.

In this tutorial we build an Express 5 service with structured JSON logs from Pino, a request ID that follows every line through AsyncLocalStorage, and distributed traces from the OpenTelemetry JavaScript SDK 3. Then we break it on purpose and measure what it costs. The headline result: with the sampler set to record nothing, tracing still cost 82% (Node 22) and 67% (Node 24) of the extra CPU that 100% sampling did.

The complete project, tests, benchmark harness and failure reproductions are on GitHub: deepakrout/node-express-observability.

Prerequisites

  • Node.js 22.15 or newer. OpenTelemetry JS SDK 3 requires it. Everything here was tested on 22.23, 24.22 and 26.13.
  • Comfortable with Express middleware and ES modules. If you need the API basics first (routing, validation, auth, error handling), start with Developing a REST API with Express.js and TypeScript. That guide uses Winston and a request ID; this one goes deeper on context propagation, tracing and cost.
  • Docker is optional, for a Jaeger UI. The repo includes a small trace receiver that needs only Node.

1. Set up the project

git clone https://github.com/deepakrout/node-express-observability.git
cd node-express-observability
npm install
npm test

Versions are pinned in package.json: Express 5.3.0, Pino 10.4.0, pino-http 11.0.0, @opentelemetry/api 1.10.0 and @opentelemetry/sdk-node 0.301.2. The layout keeps each concern in one file:

src/
  instrumentation.js    OpenTelemetry bootstrap, loaded with --import
  server.js             listen, graceful shutdown, flush
  app.js                middleware order
  logger.js             Pino config and redaction
  context.js            AsyncLocalStorage instance
  middleware/           request context, access log, errors
  routes/orders.js      an outbound fetch() and a manual span
gotchas/                one runnable script per failure
bench/                  benchmark harness and results

2. Give every request a context

AsyncLocalStorage holds a value that stays attached to one chain of async work. Put the request ID in it once, and any code downstream can log it without passing a parameter through every function.

// src/middleware/requestContext.js
import { randomUUID } from 'node:crypto';
import { requestContext } from '../context.js'; // new AsyncLocalStorage()

// Accept an upstream ID only if it is short and boring.
const SAFE_ID = /^[A-Za-z0-9._-]{8,128}$/;

export function withRequestContext(req, res, next) {
  const incoming = req.get('x-request-id');
  const requestId = incoming && SAFE_ID.test(incoming) ? incoming : randomUUID();
  req.id = requestId;
  res.setHeader('x-request-id', requestId);
  requestContext.run({ requestId }, next);
}

Validate the incoming header. It is user input that ends up in your logs. Register this middleware first so that everything after it runs inside the context.

The gotcha: callback queues swap request IDs

Promises keep context correctly. Hand-rolled callback queues do not. A resource pool, rate limiter or batcher that stores callbacks and invokes them later runs them in the context of whoever drains the queue:

release() {
  const next = this.waiting.shift();
  if (next) next(); // runs with the releasing request's context
}

// Fix: capture the caller's context when the job is queued
pool.acquire(AsyncResource.bind(job));

With 100 concurrent requests sharing a pool of five, 95 requests saw another request's ID. With AsyncResource.bind the count was zero, and a promise-based queue was also zero. This is worse than a missing ID because the log looks correct. If a library in your stack queues callbacks, write a concurrency test like the one in test/app.test.js against it.

3. Configure Pino without leaking secrets

The logger writes one JSON object per line to stdout and lets the platform ship it. The mixin function runs on every log call and copies the request context onto the line.

// src/logger.js
export function createLogger(destination) {
  return pino(
    {
      level: process.env.LOG_LEVEL || 'info',
      base: { service: process.env.OTEL_SERVICE_NAME || 'orders-api' },
      timestamp: pino.stdTimeFunctions.isoTime,
      mixin: () => ({ ...requestContext.getStore() }),
      redact: {
        paths: ['req.headers.authorization', 'req.headers.cookie',
                '*.password', '*.token'],
        censor: '[redacted]',
      },
    },
    destination,
  );
}

Now the access log. Do not ship pino-http with its default serializers. A test request carrying a bearer token and a session cookie showed both written to the log in plain text, because the default request serializer includes all headers. Allow-list what you need:

// src/middleware/httpLogger.js
export function httpLogger(logger) {
  return pinoHttp({
    logger,
    genReqId: (req) => req.id,
    autoLogging: { ignore: (req) => req.url === '/healthz' },
    customLogLevel: (req, res, err) => {
      if (err || res.statusCode >= 500) return 'error';
      if (res.statusCode >= 400) return 'warn';
      return 'info';
    },
    serializers: {
      req: (req) => ({ method: req.method, url: req.url }),
      res: (res) => ({ statusCode: res.statusCode }),
    },
  });
}

This also shrinks your log bill. In the benchmark, a line fell from 443 bytes to 231. At 1,000 requests per second and one line per request, that is about 38 GB a day versus 20 GB, even though the test client sent almost no headers. Note that URLs can carry secrets too: if yours put tokens in query strings, strip them in the serializer.

4. Add tracing with OpenTelemetry SDK 3

A trace is a tree of timed spans that shares one ID across services. The ID travels in the W3C traceparent header. The bootstrap file must run before your application imports anything:

// src/instrumentation.js (imports omitted, see the repo)
register('@opentelemetry/instrumentation/hook.mjs', import.meta.url);

const sdk = new NodeSDK({
  traceExporter: new OTLPTraceExporter(), // default http://localhost:4318
  logRecordProcessors: [],                // logs stay on stdout
  metricReaders: [],
  instrumentations: [
    new HttpInstrumentation({
      ignoreIncomingRequestHook: (req) => req.url === '/healthz',
    }),
    new ExpressInstrumentation({
      ignoreLayersType: [ExpressLayerType.MIDDLEWARE, ExpressLayerType.ROUTER],
    }),
    new UndiciInstrumentation(),          // global fetch()
    new PinoInstrumentation({ disableLogSending: true }),
  ],
});

sdk.start();
shutdownHooks.push(() => sdk.shutdown());
node --import ./src/instrumentation.js src/server.js

PinoInstrumentation adds trace_id and span_id to each log line, so you can jump from a log to its trace. The Express settings keep the useful route handler span and drop per-middleware noise.

The gotcha: ESM without the loader hook

Express is imported with import, so the SDK needs a loader hook to patch it. Without the register() line, the test app produced two spans both named GET, with no route names and no handler span. If the libraries were loaded before instrumentation and there was no hook, it produced zero spans. CommonJS apps hit the same zero when they grab express and http before the instrumentations exist.

Node 26 prints deprecation DEP0205 for module.register(). The repo offers OTEL_SYNC_HOOKS=1, which uses synchronous hooks from import-in-the-middle. It worked on all three Node versions in testing, but the OpenTelemetry ESM guide lists only hook.mjs as supported. My recommendation: keep the official hook and accept the warning until OpenTelemetry says otherwise.

5. Avoid the SDK 3 upgrade traps

SDK 3.0 merged sdk-trace-base, sdk-trace-node and sdk-trace-web into @opentelemetry/sdk-trace. Most snippets you will find online predate it. The span processor constructors changed:

// SDK 2.x
new BatchSpanProcessor(exporter);

// SDK 3.x
new BatchSpanProcessor({ exporter });

TypeScript flags the old form. Plain JavaScript does not. In testing, neither processor threw at construction and both exported zero spans. After a flush on the old BatchSpanProcessor form, the script also lingered for 30 seconds before exiting, waiting on the export timeout.

The second trap concerns configuration. A bare TracerProvider no longer reads environment variables such as the sampler settings:

process.env.OTEL_TRACES_SAMPLER = 'always_off';

new TracerProvider({ spanProcessors: [processor] }); // exported 100 of 100
new NodeSDK({ spanProcessors: [processor] });        // exported 0 of 100

If you control sampling through deployment config, use NodeSDK, or set the sampler in code. After upgrading, check your span volume, because a silently ignored sampler shows up on the invoice first.

6. Add manual spans and record errors

Instrumentation libraries see HTTP calls and routes. They cannot see your business logic, so wrap the parts you would want timed:

// src/routes/orders.js
const upstream = await fetch(`${inventoryUrl()}/inventory/${id}`, {
  headers: { 'x-request-id': req.id },
  signal: AbortSignal.timeout(2000),
});

const total = tracer.startActiveSpan('order.price', (span) => {
  try {
    const value = priceFor(id); // inline in the repo
    span.setAttribute('order.total', value);
    return value;
  } finally {
    span.end();
  }
});
logger.info({ orderId: id, total }, 'order priced');

Express 5 forwards rejected promises to the error handler, so one place can mark the span and write one error log:

// src/middleware/errorHandler.js
if (status >= 500) {
  const span = trace.getActiveSpan();
  span?.recordException(err);
  span?.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
  logger.error({ err }, 'request failed');
}

7. Shut down without losing data

Spans are exported in batches, so some are always sitting in memory. After 50 requests followed immediately by SIGTERM, the collector received 0 spans both with no signal handler and with a handler that only called process.exit(). Draining the server and awaiting sdk.shutdown() delivered all 300.

// src/server.js
async function shutdown(reason, exitCode = 0) {
  if (closing) return;
  closing = true;
  logger.info({ reason }, 'shutting down');
  setTimeout(() => process.exit(1), 8000).unref(); // beat the platform's kill
  await new Promise((resolve) => server.close(resolve));
  try {
    await Promise.all(shutdownHooks.map((hook) => hook()));
  } catch (err) {
    logger.error({ err }, 'telemetry shutdown failed');
    exitCode = 1;
  }
  destination.flushSync();
  process.exit(exitCode);
}
process.on('SIGTERM', () => shutdown('SIGTERM'));

The handler only helps if the signal reaches Node. In containers, run node directly instead of npm start; the Cloud Run deployment guide measures that exact SIGTERM problem. For image basics, see Docker: A Practical Guide for Developers.

Synchronous or buffered logs?

Pino can buffer writes. We logged 1,000 lines in one burst with a 4 KB buffer and then ended the process:

How the process ended

sync: true

sync: false

process.exit()

1000

1000

Uncaught exception

1000

1000

SIGTERM with no handler

1000

47

SIGKILL (as the OOM killer sends)

1000

47

This is a worst case, since the event loop had no chance to drain. Still, the lines you lose in a kill are the ones that explain it. Buffering bought little in the HTTP benchmark below, so the project stays synchronous by default.

8. Verify the whole path

# terminal 1: prints every span it receives
node scripts/otlp-sink.js

# terminal 2
npm start
curl -i -H 'x-request-id: demo-request-0001' localhost:3000/orders/42

You should see three log lines with the same requestId and trace_id: the inventory request, the pricing message and the order request. The sink shows the server spans, the outbound fetch and order.price in one trace. Then run npm run gotchas to reproduce the failures in this article. For a UI, docker compose up -d starts Jaeger on port 16686 (that compose file is the one part I have not run).

9. Measure what observability costs

The benchmark serves one small JSON route with one log line per request. The server is pinned to one vCPU of a 2.10 GHz Xeon virtual machine; the load generator (autocannon, 50 connections) and trace receiver share a second. Logs go to a memory-backed file. Each figure is the median of five 8-second runs after a 5-second warm-up. CPU is server process time per request.

Configuration

Node 22 req/s

Node 22 CPU µs

Node 24 req/s

Node 24 CPU µs

Node 24 p99 ms

No logging

7,352

135

19,494

50

7

Morgan (JSON format)

4,550

208

12,646

76

11

Winston (JSON)

5,822

167

12,657

77

10

Pino, sync

6,132

161

13,733

71

9

Pino, buffered

5,824

167

14,685

66

8

pino-http, defaults

4,365

226

13,865

69

8

Project logging (context + slim pino-http)

3,259

301

11,735

83

10

+ tracing, 100% sampled

2,006

487

4,107

234

53

+ tracing, 10% sampled

1,967

491

4,595

214

32

+ tracing, always_off

2,156

453

5,312

185

25

+ all auto-instrumentations, 100%

1,404

695

2,081

456

125

Read this with care. A near-empty route makes overhead look as large as it ever will, and a shared VM is noisy: on Node 22, Pino ranged from 4,761 to 6,586 requests per second across rounds and Winston from 4,065 to 6,199. Small gaps mean nothing.

What I would do with these numbers

  • Do not pick a logger on speed alone. With one line per HTTP request, Pino and Winston were effectively tied. I still choose Pino for redaction, mixins and clean JSON by default.
  • Treat sampling as a storage control first. On Node 24, tracing added about 151 µs per request at 100%, 131 µs at 10% and 102 µs at always_off. On Node 22, 10% and 100% were indistinguishable (about 190 µs), and off still added 153 µs. Instrumentation runs even when the trace is discarded. Even OTEL_SDK_DISABLED=true is not free: in a separate three-round run it still added about 50 µs on Node 22 and 34 µs on Node 24 over logging alone, against 241 µs and 174 µs at 100% sampling in that run. For zero overhead, do not preload the bootstrap file.
  • Budget in CPU, not percentages. At 500 requests per second, 151 µs is about 7.5% of one core. That is often a fair price.
  • Hand-pick instrumentations. The auto bundle emitted eight spans per request against two, and only 76% (Node 22) and 83% (Node 24) of server spans arrived. A debug-level run showed why: Dropped N spans because maxQueueSize reached. Its default settings overflowed under this load, with nothing visible at normal log levels.
  • Test Node 24. It was far faster in every row. Node 24 made AsyncContextFrame the default for AsyncLocalStorage, which may contribute, though this benchmark did not isolate the cause. A separate run put the cost of request context on top of logging at about 35 µs on Node 22 and 12 µs on Node 24.

Reference: symptoms, causes and fixes

Symptom

Likely cause

Fix

Spans named only GET

ESM loader hook missing

Register hook.mjs, preload with --import

No spans at all

Libraries loaded before instrumentation

Preload the bootstrap file

No spans after SDK 3 upgrade

2.x processor signature

Pass { exporter }

Sampler variable ignored

Bare TracerProvider

Use NodeSDK or set it in code

Last spans missing after deploys

No flush on SIGTERM

Await sdk.shutdown()

Gaps under load

Span queue full

Fewer instrumentations; check OTEL_LOG_LEVEL=warn

Wrong request ID in logs

Callback queue

AsyncResource.bind

Last log lines missing

Buffered destination, hard exit

sync: true, handle signals

Tokens in logs

Default serializers

Allow-list fields, add redact

What's next

  • Add RED metrics (rate, errors, duration) with an OpenTelemetry metric reader, then measure the added cost with the same harness.
  • Put an OpenTelemetry Collector in front of your backend and try tail sampling, so errors and slow requests are kept.
  • Carry context through a queue by writing traceparent into job metadata and restoring it in the worker.
  • Centralize logs on your cluster. The Kubernetes guide covers the platform that would collect this stdout stream.

Further reading

Wrapping up

Good observability for an Express service is a short list: one context per request, structured logs with an allow-list, a tracing bootstrap that loads first, and a shutdown path that flushes. Then verify it, because most failures here raise no error. Clone the GitHub repository, run npm run gotchas against your own versions, and rerun the benchmark on your hardware before you trust anyone's numbers, including these.

Share

Comments (0)

Join the conversation

Sign in to leave a comment on this post.

No comments yet. to be the first!