Courses / Node.js: From First Script to Production / Chapter 23
Module 9 · Tests, types and operations · Chapter 23 of 27
Observability: Structured Logs, Metrics and Traces
Builds on Working with Databases: A REST API on PostgreSQL. Next up: Scaling and Deploying: Statelessness, Graceful Shutdown and Containers.
Part 1 · Structured logs with pino
Why plain text logs stop working
At nine in the morning on results day, an exam site shows errors to some students, and the log is full of lines like payment failed for order. A plain sentence cannot be searched for which order, which student or how long it took.
Observability is how well you can understand what a running system is doing from the data it emits. Three kinds of data do most of the work: logs, which are records of events; metrics, which are numbers measured over time; and traces, which follow one request across several services. This lesson covers logs. Later lessons cover request ids, metrics, health checks and traces.
A structured log writes each event as data with named fields, not as a sentence. The usual format is JSON lines: one JSON object per line. A log tool can then filter on orderId or level without parsing English. pino is a Node logger built for this. Its API documentation gives standard output as the default destination, and its README recommends that sending, reformatting and other processing of logs happen outside the application process. A common practice is to write to stdout and let the platform that runs the service collect the lines and ship them to wherever they are searched.
Levels, fields and child loggers
Every line has a level, a number that says how serious it is. In pino, trace is 10, debug 20, info 30, warn 40, error 50 and fatal 60, and the level option sets the minimum that is written. The default is info, so debug lines are dropped unless you ask for them.
You pass an object first and a message second: logger.info({ queueDepth: 120 }, 'kitchen queue is long'). The object's keys become fields. A child logger, made with logger.child({ orderId: 'F-1001' }), adds fixed fields to every line it writes, so code that handles one order does not repeat the id on each call.
Logging an Error object produces an err field with the type, message and stack, which a log tool can show properly.
import pino from 'pino'; const logger = pino({ base: { svc: 'orders' }, timestamp: false, level: process.env.LOG_LEVEL ?? 'info', redact: ['req.headers.authorization', 'password'], }); logger.debug('cache miss for menu'); logger.info('server started'); logger.warn({ queueDepth: 120 }, 'kitchen queue is long'); const order = logger.child({ orderId: 'F-1001' }); order.info('order placed'); const err = new Error('payment gateway busy'); err.stack = 'Error: payment gateway busy\n at pay (orders.js:42:11)'; order.error(err, 'payment failed'); logger.info({ req: { headers: { authorization: 'Bearer abc.def.ghi' } }, password: 'hunter2', }, 'incoming request');
The script sets base to an object with only the service name. By default, the pino documentation says, base holds the process id and hostname, which you often want in production. timestamp: false removes the time field so that this output is the same on every run. In a real service you keep the timestamp.
{"level":30,"svc":"orders","msg":"server started"}
{
"level": 40,
"svc": "orders",
"queueDepth": 120,
"msg": "kitchen queue is long"
}
{"level":30,"svc":"orders","orderId":"F-1001","msg":"order placed"}
{
"level": 50,
"svc": "orders",
"orderId": "F-1001",
"err": {
"type": "Error",
"message": "payment gateway busy",
"stack": "Error: payment gateway busy\n at pay (orders.js:42:11)"
},
"msg": "payment failed"
}
{
"level": 30,
"svc": "orders",
"req": {
"headers": {
"authorization": "[Redacted]"
}
},
"password": "[Redacted]",
"msg": "incoming request"
}pino 10.4.0 on Node 24.18.0. Long lines are re-indented to fit. The `debug` call printed nothing.
Redaction, labels and levels from the environment
Logs are copied to many places, so they must never hold secrets. pino's redact option takes a list of paths, such as req.headers.authorization, and replaces the value with [Redacted] by default. In the output above, both the bearer token and the password were replaced. The documentation warns never to let user input choose the redacted paths.
Redaction is a safety net. The better habit is to not log secrets and personal data in the first place: log an order id, not a phone number or card detail.
By default the level field is a number. If your log tool prefers a label, a formatters.level function can return one.
import pino from 'pino'; const logger = pino({ base: undefined, timestamp: false, formatters: { level: (label) => ({ level: label }) }, }); logger.info({ orderId: 'F-1001' }, 'order placed');
{"level":"info","orderId":"F-1001","msg":"order placed"}Node 24.18.0.
Read the minimum level from the environment, as the script above does with LOG_LEVEL. Then you can turn on debug for one instance while investigating, without a new release. Setting LOG_LEVEL=debug on the same script made the debug line appear.
{"level":20,"svc":"orders","msg":"cache miss for menu"}The first line of the output with `LOG_LEVEL=debug`.
Why log JSON lines instead of sentences?
- Each field is named, so a log tool can filter and group on
orderId,levelorstatuswithout parsing English. A sentence can only be searched as text.
What does a pino child logger do?
- It adds fixed fields, such as an order id, to every line it writes, so code handling one order does not repeat the id in each call.
A request body with a card number reaches a log call. What are two protections?
- Do not log the field at all, and add its path to
redactas a safety net so the value is replaced with[Redacted].
Part 2 · Request ids across async code
Following one request through many log lines
A server handles many requests at the same time. Their log lines interleave, so a line reading loaded from database does not tell you whose request it was. The fix is a request id: a value made for each incoming request, put on every log line that request causes. Searching for one id then returns that request's whole story.
Passing the id to every function as an argument works, but it clutters every signature. Node offers AsyncLocalStorage in node:async_hooks. It creates a store that stays attached to a chain of asynchronous operations: you call als.run(store, callback), and any code run from that callback, even after awaits, timers and callbacks, can read the same store with als.getStore(). The Node.js documentation says it is stable and recommends it over building your own on async hooks, and its own example is a logger that tags messages with a request id.
The context middleware
The middleware below takes the id from an x-request-id header when a caller sent one, so that an id made at the edge is kept. It accepts the header only if it is 1 to 64 letters, digits, underscores or dashes, because every log line repeats the id and a client could otherwise send thousands of odd characters. Otherwise it makes a new one with randomUUID(). It echoes the id in a response header, then calls next() inside als.run. Everything that follows runs inside that store.
The logger uses pino's mixin option. A mixin is a function that pino calls on every log call. It returns an object whose fields are added to the line. Here it reads the store and adds the request id.
import { AsyncLocalStorage } from 'node:async_hooks'; import { randomUUID } from 'node:crypto'; import pino from 'pino'; export const als = new AsyncLocalStorage(); export const log = pino({ base: undefined, timestamp: false, mixin: () => ({ reqId: als.getStore()?.requestId }), }); const SAFE_ID = /^[A-Za-z0-9_-]{1,64}$/; export function requestContext(req, res, next) { const sent = req.headers['x-request-id'] ?? ''; const requestId = SAFE_ID.test(sent) ? sent : randomUUID(); res.setHeader('x-request-id', requestId); als.run({ requestId }, next); }
No other code needs to know about the id. A handler just calls log.info('loaded from database').
Two requests at once
The route below simulates a database wait with a timer. The client sends two requests together: A waits 60 ms and B waits 10 ms, so their steps interleave.
import express from 'express'; import { log, requestContext } from './als.mjs'; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const app = express(); app.use(requestContext); app.get('/orders/:id', async (req, res) => { log.info({ orderId: req.params.id }, 'order requested'); await sleep(Number(req.query.delay)); log.info('loaded from database'); await sleep(10); log.info('response ready'); res.json({ ok: true }); }); app.listen(55651, '127.0.0.1');
const base = 'http://127.0.0.1:55651'; const call = (id, delay) => fetch(`${base}/orders/${id}?delay=${delay}`, { headers: { 'x-request-id': `req-${id}` }, }); await Promise.all([call('A', 60), call('B', 10)]);
{"level":30,"reqId":"req-A","orderId":"A","msg":"order requested"}
{"level":30,"reqId":"req-B","orderId":"B","msg":"order requested"}
{"level":30,"reqId":"req-B","msg":"loaded from database"}
{"level":30,"reqId":"req-B","msg":"response ready"}
{"level":30,"reqId":"req-A","msg":"loaded from database"}
{"level":30,"reqId":"req-A","msg":"response ready"}Express 5.3.0, pino 10.4.0, Node 24.18.0. Request B finishes before request A.
Every line carries the id of its own request, although B's lines come between A's. Reading the lines for req-A alone gives A's story.
Passing the id to another service
A request often calls other services, and their logs need the same id, or the trail stops at the first hop. The simple rule is to send the id in the x-request-id header on every outgoing call and have each service apply the same middleware. The route below reads the id from the store when it calls payments, which is a separate Node process on its own port, and logs before and after.
import express from 'express'; import { als, log, requestContext } from './als.mjs'; const app = express(); app.use(requestContext); app.get('/orders/:id', async (req, res) => { log.info({ orderId: req.params.id }, 'order requested'); const reply = await fetch('http://127.0.0.1:55652/charge', { method: 'POST', headers: { 'x-request-id': als.getStore().requestId }, }); const { receipt } = await reply.json(); log.info({ receipt }, 'paid'); res.json({ receipt }); }); app.listen(55651, '127.0.0.1');
The payments service writes its own log line with the header it received.
import express from 'express'; const app = express(); app.post('/charge', (req, res) => { console.log(JSON.stringify({ svc: 'payments', reqId: req.headers['x-request-id'], traceparent: req.headers.traceparent, })); res.json({ receipt: 'R-100' }); }); app.listen(55652, '127.0.0.1');
{"level":30,"reqId":"req-77","orderId":"9","msg":"order requested"}
{"level":30,"reqId":"req-77","receipt":"R-100","msg":"paid"}The orders service's log. A request with `x-request-id: req-77` was sent with curl.
{"svc":"payments","reqId":"req-77"}The payments service's log for the same request.
Both services logged req-77. A search for that one string over the logs of both services returns the request's steps in order. The id comes from the first service that sees the request, and each service passes it on. Do not trust a client's id for anything that matters, such as security decisions: it is only a label for finding lines.
Why not a module variable
It is tempting to store the id in a variable at module level, set by the middleware. It fails as soon as two requests overlap. The next app does exactly that.
import express from 'express'; import pino from 'pino'; let currentId; const log = pino({ base: undefined, timestamp: false, mixin: () => ({ reqId: currentId }), }); const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const app = express(); app.use((req, res, next) => { currentId = req.headers['x-request-id']; next(); }); app.get('/orders/:id', async (req, res) => { log.info({ orderId: req.params.id }, 'order requested'); await sleep(Number(req.query.delay)); log.info('loaded from database'); res.json({ ok: true }); }); app.listen(55651, '127.0.0.1');
{"level":30,"reqId":"req-A","orderId":"A","msg":"order requested"}
{"level":30,"reqId":"req-B","orderId":"B","msg":"order requested"}
{"level":30,"reqId":"req-B","msg":"loaded from database"}
{"level":30,"reqId":"req-B","msg":"loaded from database"}The same two requests against the module-variable version.
The later lines, loaded from database, both say req-B. The variable was overwritten by request B while A was waiting, so A's line got B's id. Only B's line is right. This is the bug that AsyncLocalStorage prevents: each request has its own store, and the store follows the request through every await.
What problem does a request id solve?
- Log lines from many concurrent requests interleave. An id on every line lets you filter to one request and read its whole story.
What does AsyncLocalStorage.run(store, callback) guarantee?
- Code started from the callback, including code after
awaits and in timers and callbacks, sees the same store throughgetStore(), without passing it as an argument.
Why does a module-level currentId variable give wrong ids?
- It is shared by all requests. When a second request sets it while the first is waiting, the first request's later log lines carry the second request's id.
Part 3 · Metrics that matter
Numbers over time
Logs record single events. Metrics are numbers sampled over time, cheap to store and fast to graph and alert on. A dashboard that says the error rate rose at 9:02 is a metric. The log lines then tell you which errors.
A well-known guide on monitoring distributed systems, the Google SRE book, names four golden signals: latency, traffic, errors and saturation. Latency is how long requests take, and the book says to separate the latency of successful requests from the latency of failed ones, adding that a slow error is worse than a fast error. Traffic is the demand on the system, such as requests per second. Errors are failing requests. Saturation is how full the system is. For a Node service, good saturation signals are event loop delay and heap use. Request-driven services are often summarised as rate, errors and duration, which are the first three signals.
Counters, gauges and histograms
Metric libraries offer a few types. A counter only goes up, such as total requests. A gauge goes up and down, such as heap bytes in use. A histogram counts observations into buckets, such as requests that took up to 10 ms, up to 50 ms, and so on, and it also keeps a running sum and count. From a histogram a monitoring system can estimate percentiles, such as the p99, which a plain average hides.
prom-client is the usual metrics library for Node. It speaks the Prometheus text format. Prometheus is a monitoring system that scrapes a /metrics URL from your service at an interval. The prom-client documentation says the library bundles no web server and that you respond to scrapes with await registry.metrics(). It also says default metrics are collected on scrape and not on a timer.
Calling collectDefaultMetrics() registers standard process and Node metrics, including event loop lag, handles and garbage collection. The module below creates a registry, turns those on, and adds a histogram for request duration, labelled by route and status. A label is a key and value that splits one metric into series.
import client from 'prom-client'; export const registry = new client.Registry(); client.collectDefaultMetrics({ register: registry }); const duration = new client.Histogram({ name: 'http_request_duration_seconds', help: 'Request time by route and status', labelNames: ['route', 'status'], buckets: [0.01, 0.05, 0.1, 0.5, 1], registers: [registry], }); const byPattern = (req) => req.route?.path ?? 'unmatched'; export function metricsMiddleware(routeOf = byPattern) { return (req, res, next) => { const end = duration.startTimer(); res.on('finish', () => { end({ route: routeOf(req), status: res.statusCode }); }); next(); }; } export async function metricsHandler(req, res) { res.set('content-type', registry.contentType); res.send(await registry.metrics()); }
In a real service you also label by method; it is left out so that the lines below fit the page. The middleware starts a timer when a request arrives. When the response finishes, it stops the timer with the labels for that request.
One label, many series
Labels are the dangerous part of metrics. Each distinct set of label values is a separate time series that the monitoring system stores forever. So a label must have a small, fixed set of values. A route pattern, such as /orders/:id, is fine. A raw URL, such as /orders/9187, is not: every order id makes a new series, and the store grows without limit. This is called a cardinality problem.
The label function above uses req.route.path, which Express fills with the pattern. An unmatched path gets the value unmatched. The test app below sends four requests to different order ids and one to a path that does not exist. A second run does the same with the raw URL as the label.
import express from 'express'; import { metricsHandler, metricsMiddleware } from './metrics.mjs'; const raw = (req) => req.originalUrl; const mode = process.env.ROUTE_LABEL === 'raw' ? raw : undefined; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const app = express(); app.use(metricsMiddleware(mode)); app.get('/orders/:id', async (req, res) => { await sleep(Number(req.params.id) * 20); res.json({ id: req.params.id }); }); app.get('/metrics', metricsHandler); app.listen(55651, '127.0.0.1');
http_request_duration_seconds_count{route="/orders/:id",status="200"} 4
http_request_duration_seconds_count{route="unmatched",status="404"} 1
http_request_duration_seconds_count{route="/orders/1",status="200"} 1
http_request_duration_seconds_count{route="/orders/2",status="200"} 1
http_request_duration_seconds_count{route="/orders/3",status="200"} 1
http_request_duration_seconds_count{route="/orders/4",status="200"} 1
http_request_duration_seconds_count{route="/nope",status="404"} 1The first group is labelled by route pattern, the second by raw URL. Request counts per series.
By pattern, the four order requests landed in one series with a count of 4, and the missing path went to unmatched. By raw URL, there was a new series for every id, and the real traffic pattern was lost. This is why the route label comes from the router and never from the request URL.
What the endpoint prints
The scrape endpoint returns plain text. Each metric has a # TYPE line and then one line per series. The default metrics from collectDefaultMetrics() include the names below, which come from the run of the test app.
# TYPE process_cpu_user_seconds_total counter # TYPE process_resident_memory_bytes gauge # TYPE nodejs_eventloop_lag_seconds gauge # TYPE nodejs_eventloop_lag_p99_seconds gauge # TYPE nodejs_active_handles gauge # TYPE nodejs_heap_size_used_bytes gauge
prom-client 15.1.3. A few of the 163 lines served by the endpoint, picked with grep.
The response header says which format it is. The library defaults to the Prometheus text format, version 0.0.4.
Content-Type: text/plain; version=0.0.4; charset=utf-8
The `content-type` header from the `/metrics` response.
Histogram output is a set of cumulative buckets. Each le value, short for less than or equal, counts the requests at or under that many seconds. The four requests slept for 20, 40, 60 and 80 ms.
import fs from 'node:fs'; const text = fs.readFileSync(process.argv[2], 'utf8'); const want = 'http_request_duration_seconds'; for (const line of text.split('\n')) { const isBucket = line.startsWith(`${want}_bucket`); if (!isBucket || !line.includes('/orders/:id')) { continue; } const le = line.match(/le="([^"]+)"/)[1]; console.log(`le ${le.padEnd(5)} ${line.split(' ').pop()}`); }
le 0.01 0 le 0.05 2 le 0.1 4 le 0.5 4 le 1 4 le +Inf 4
Buckets for the route `/orders/:id`, one run. The script prints one line per `le` bound.
Two requests finished within 50 ms and all four within 100 ms. The counts only grow as le grows, which is why the last bucket, +Inf, equals the total count. Choose bucket bounds around the response times you care about, such as your limit for a good response.
Name the four golden signals and say which one a slow error makes worse.
- Latency, traffic, errors and saturation. The SRE book says a slow error is worse than a fast error, so latency should be tracked separately for failed and successful requests.
What is the difference between a counter and a gauge?
Part 4 · Health, liveness and readiness
Liveness and readiness
A platform that runs your service needs to ask it two different questions. Liveness: is the process alive, or stuck so that only a restart helps? Readiness: can it serve requests right now? The Kubernetes documentation puts it this way. A failing liveness probe makes the kubelet kill the container and restart it. A pod whose containers are not ready receives no traffic through Kubernetes Services. The page adds that the two probes do not depend on each other, so a failing readiness check on its own does not restart anything.
The difference matters in a failure. Suppose the database is down. If the liveness check asks the database, every instance fails liveness and is restarted, which does not fix the database and adds load when it returns. If the readiness check asks the database, the instances stop receiving traffic and wait, and no restart happens. So liveness checks only that the process can answer, and readiness checks what is needed to do real work.
const withTimeout = (work, ms) => Promise.race([ work, new Promise((_, reject) => { setTimeout(() => reject(new Error('timed out')), ms).unref(); }), ]); export function healthRoutes(app, { state, checkDb }) { app.get('/healthz', (req, res) => { res.json({ status: 'alive' }); }); app.get('/readyz', async (req, res) => { if (state.shuttingDown) { return res.status(503).json({ status: 'draining' }); } try { await withTimeout(checkDb(), 300); res.json({ status: 'ready' }); } catch (err) { console.error('readiness check failed:', err.code ?? err.message); res.status(503).json({ status: 'not ready' }); } }); }
The readiness check wraps the database call in a 300 ms timeout. A database that hangs must give a quick 503, and never a probe that hangs too. The timeout stops the probe from waiting but does not cancel the query behind it, so a pool with a connection timeout, as in the databases chapter, keeps such queries from piling up. The response body says only not ready, not why: the reason goes to the log, since a health endpoint is often reachable by more people than the logs.
Flipping readiness
A readiness check also supports shutdown. When the process gets SIGTERM, it sets a flag and starts answering 503, so the platform stops sending new requests while the ones in progress finish. The script below runs five situations against the real lab database. For a database that refuses connections it uses a pool aimed at a closed port, and for one that hangs it uses a promise that never settles. It triggers shutdown with process.emit('SIGTERM'), because on Windows a real signal does not run a handler. The next chapter shows a real signal on Linux.
import express from 'express'; import pg from 'pg'; import { healthRoutes } from './health.mjs'; const conn = { host: '127.0.0.1', user: 'postgres', max: 1 }; const good = new pg.Pool({ ...conn, port: 55650 }); const dead = new pg.Pool({ ...conn, port: 55659 }); const state = { shuttingDown: false }; let pool = good; let hang = false; const never = () => new Promise(() => {}); const checkDb = () => (hang ? never() : pool.query('select 1')); const app = express(); healthRoutes(app, { state, checkDb }); const server = app.listen(55651, '127.0.0.1'); process.once('SIGTERM', () => { state.shuttingDown = true; }); async function probe(label) { const base = 'http://127.0.0.1:55651'; for (const path of ['/healthz', '/readyz']) { const res = await fetch(base + path); const body = JSON.stringify(await res.json()); console.log(label.padEnd(18), path.padEnd(9), res.status, body); } }
The checks then run in sequence, with the database, the shutdown flag and the probes changed between steps.
await probe('all fine'); pool = dead; await probe('database refuses'); pool = good; hang = true; await probe('database hangs'); hang = false; await probe('recovered'); process.emit('SIGTERM'); await probe('after SIGTERM'); server.close(); server.closeAllConnections();
all fine /healthz 200 {"status":"alive"} all fine /readyz 200 {"status":"ready"} database refuses /healthz 200 {"status":"alive"} database refuses /readyz 503 {"status":"not ready"} database hangs /healthz 200 {"status":"alive"} database hangs /readyz 503 {"status":"not ready"} recovered /healthz 200 {"status":"alive"} recovered /readyz 200 {"status":"ready"} after SIGTERM /healthz 200 {"status":"alive"} after SIGTERM /readyz 503 {"status":"draining"}
Express 5.3.0, pg 8.23.1, Node 24.18.0 against the lab database.
Liveness stayed 200 in every row, including during shutdown. Readiness went 503 when the database refused, when it hung, and after the shutdown signal, and came back to 200 when the database recovered.
Wiring the probes
A platform such as Kubernetes calls your endpoints on a schedule. The Kubernetes documentation shows an HTTP probe as an httpGet with a path and a port, a delay before the first check and a period between checks, and says that any status from 200 up to but not including 400 counts as success. The configuration below points the two probes at the endpoints from this lesson. It is shown and not run, since there is no cluster here, and it follows the shape of the documentation's own example.
readinessProbe:
httpGet:
path: /readyz
port: 3000
initialDelaySeconds: 3
periodSeconds: 5
failureThreshold: 2
livenessProbe:
httpGet:
path: /healthz
port: 3000
initialDelaySeconds: 10
periodSeconds: 10
failureThreshold: 3The readiness probe runs more often than the liveness probe, so a pod that recovers starts receiving traffic soon. The liveness probe is slower and more patient, so that a short stall does not restart a healthy process. Pick the numbers from how long your service takes to start and how quickly you want it to rejoin.
Keep the checks light. A probe that runs a heavy query every few seconds, from every instance, adds load of its own. Check what the instance needs to do its work, for example one cheap query on a connection from the pool. The probe then also notices a pool that is exhausted, which is a real reason not to send traffic.
What is the difference between a liveness and a readiness check?
- Liveness asks whether the process should be restarted. Readiness asks whether it can serve traffic now. A failed readiness check only stops traffic, while a failed liveness check causes a restart.
Why should a liveness check not call the database?
- If the database is down, every instance would fail liveness and be restarted, which does not help and adds load. Keep liveness to the process itself and use readiness for dependencies.
Why does the readiness check use a timeout?
- A hung dependency must produce a quick 503. Without a timeout, the probe would hang and the platform would see a timeout rather than a clear answer.
Part 5 · Tracing with OpenTelemetry
Following a request across services
One order request now goes through the orders API and calls a payments service. Logs with the same request id show it, but you cannot see how long each step took or how the calls nest. A trace records that. It is the whole journey of one request, made of spans. A span is one timed operation, with a name, a start, a duration and a parent span that started it. The first span of a trace is the root.
OpenTelemetry, shortened to OTel, is a vendor-neutral set of APIs and tools for producing traces, metrics and logs. Your service creates the data and an exporter sends it to a backend. Here the exporter just prints.
Context travels in a header
For a trace to cross from one service to another, the caller sends the trace context along with the request. The W3C Trace Context standard defines a header for it, traceparent, with four fields joined by dashes: a version, a 32-character trace-id shared by the whole trace, a 16-character parent-id, which is the caller's span, and trace-flags, whose lowest bit says the request is sampled. For example, 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01 is from the specification. The receiving service starts its spans as children of that parent.
Setting it up
The OpenTelemetry getting-started page for Node uses a small file that starts the SDK, loaded before your app with --import. This lab follows it, with traces only.
import { NodeSDK } from '@opentelemetry/sdk-node'; import { ConsoleSpanExporter } from '@opentelemetry/sdk-trace'; import { getNodeAutoInstrumentations, } from '@opentelemetry/auto-instrumentations-node'; const sdk = new NodeSDK({ traceExporter: new ConsoleSpanExporter(), instrumentations: [getNodeAutoInstrumentations()], }); sdk.start();
getNodeAutoInstrumentations() turns on a set of instrumentations that patch common libraries, so HTTP calls, fetch and Express routes produce spans without code changes. ConsoleSpanExporter prints each finished span. The page says that an application written as ES modules needs a loader hook to be instrumented properly. In this lab the app is ES modules, and the HTTP, router, fetch and network spans still appeared on Node 24.18.0 without one, because the libraries patched here are core modules, Express and fetch. A library that is published as ES modules only may behave differently, so check your own app the same way.
The orders API puts the trace id on its log lines too, using trace.getActiveSpan() from @opentelemetry/api inside the logger's mixin. That joins logs and traces: from a slow trace you search the logs for its id.
import { trace } from '@opentelemetry/api'; import express from 'express'; import pino from 'pino'; import { als, requestContext } from './als.mjs'; const log = pino({ base: undefined, timestamp: false, mixin: () => ({ reqId: als.getStore()?.requestId, traceId: trace.getActiveSpan()?.spanContext().traceId, }), }); const app = express(); app.use(requestContext); app.get('/orders/:id', async (req, res) => { log.info({ orderId: req.params.id }, 'order requested'); const reply = await fetch('http://127.0.0.1:55652/charge', { method: 'POST', headers: { 'x-request-id': als.getStore().requestId }, }); const { receipt } = await reply.json(); log.info({ receipt }, 'paid'); res.json({ receipt }); }); app.listen(55651, '127.0.0.1');
import express from 'express'; const app = express(); app.post('/charge', (req, res) => { console.log(JSON.stringify({ svc: 'payments', reqId: req.headers['x-request-id'], traceparent: req.headers.traceparent, })); res.json({ receipt: 'R-100' }); }); app.listen(55652, '127.0.0.1');
One request, two services
The script starts the two services, each with its own OTEL_SERVICE_NAME, and sends one request carrying x-request-id: req-77. Each span batch is flushed every 200 ms in the lab so that it prints quickly. Here are the log lines of the API.
{
"level": 30,
"reqId": "req-77",
"traceId": "96d516d5c2acf952c27c7f2c17bf422e",
"orderId": "9",
"msg": "order requested"
}
{
"level": 30,
"reqId": "req-77",
"traceId": "96d516d5c2acf952c27c7f2c17bf422e",
"receipt": "R-100",
"msg": "paid"
}Node 24.18.0. The trace id is random on every run. This is one real run.
The two lines share a request id and a trace id. Payments received this on its side.
svc: payments reqId: req-77 traceparent: 00-96d516d5c2acf952c27c7f2c17bf422e-84454f0a8f2ece77-01
What the payments service logged for the same request, one field per line. The service prints it as one JSON line.
The traceparent it received carries the same trace id, and its parent id is the id of the API's fetch span. A short script reads the exporter output of both services and lists every span with its parent.
import fs from 'node:fs'; import vm from 'node:vm'; const KINDS = ['internal', 'server', 'client']; function spansIn(file) { const out = []; let block = null; for (const line of fs.readFileSync(file, 'utf8').split('\n')) { if (line === '{' && block === null) block = ['{']; else if (block) { block.push(line); if (line === '}') { out.push(vm.runInNewContext(`(${block.join('\n')})`)); block = null; } } } return out; }
The rest of the script sorts the spans by start time and prints one line each.
const spans = process.argv.slice(2).flatMap(spansIn); spans.sort((a, b) => a.timestamp - b.timestamp); const cols = ['service', 'trace', 'span', 'parent', 'kind', 'name']; console.log(cols.map((c, i) => c.padEnd(i < 5 ? 9 : 0)).join('')); for (const s of spans) { const svc = s.resource.attributes['service.name']; const name = s.name .replace('request handler - ', 'handler ') .replace('middleware - ', 'mw '); console.log([ svc, s.traceId.slice(0, 8), s.id.slice(0, 8), (s.parentSpanContext?.spanId ?? '-').slice(0, 8), KINDS[s.kind] ?? s.kind, ].map((c) => c.padEnd(9)).join('') + name); }
service trace span parent kind name orders 96d516d5 010775eb - server GET orders 96d516d5 8183b8a8 010775eb internal mw requestContext orders 96d516d5 319167be 010775eb internal handler /orders/:id orders 96d516d5 84454f0a 319167be client POST orders 96d516d5 7050d4f6 319167be internal tcp.connect payments 96d516d5 2996579f 84454f0a server POST payments 96d516d5 26484f76 2996579f internal handler /charge
Ids are shortened to 8 characters. Span ids and trace ids differ on every run.
Reading the trace
All seven spans share one trace id. The root is the server span GET in the orders service. Under it are the router spans, the client span POST for the call to payments and a tcp.connect span for the network connection. The payments server span has the client span as its parent, and that link is the traceparent header at work. A trace viewer draws this as a tree with the time of each span.
One raw span from the exporter, with a few of its fields:
{
name: 'GET',
kind: 1,
traceId: '96d516d5c2acf952c27c7f2c17bf422e',
id: '010775ebfd09a28b',
attrs: { method: 'GET', path: '/orders/9', status: 200 }
}The root span of the request. The exporter prints much more, including host and process attributes.
Watch for the same id appearing in every hop and every log line
Read it as steps
The id and the trace context travel with the request, so every log line and span can be joined later.
The exporter's full output also holds host names, process paths and user names, so never send it to a place you do not control. A real setup sends spans to a collector and a backend under your control.
All chapters · Previous: TypeScript for Node: Type Stripping, tsconfig and Typed Handlers