Structured Logging in Node.js and NestJS with Pino 10: How We Add Request IDs, Redact Secrets, and Keep Error Stacks
Table of Contents
About the Author

Ahmed Mahmoud
Author & Developer
Software engineer passionate about web development and user experience design.
Founder of Devya · eng-ahmed.com ↗Headline: Structured logging writes every log event as a JSON object with stable fields such as level, time, msg and requestId, so a log backend can filter and join lines instead of grepping text. In Node.js and NestJS we use Pino 10 for this, and the real work is not installing it: it is carrying a request ID through async code, redacting the headers pino-http logs by default, and passing errors so the stack trace survives.
Our Node.js services used to log with console.log and template strings. That works until two requests run at once: the lines interleave, nothing ties a database error to the HTTP request that caused it, and the only query language is grep. Pino, a low-overhead JSON logger for Node.js, fixed the format quickly; getting the fields right took longer. These are our notes from moving Express and NestJS APIs to Pino 10.3 with pino-http and nestjs-pino.
Key takeaways
• One JSON object per line: Pino writes newline-delimited JSON (NDJSON) with a numeric level (30 is info, 50 is error), a millisecond time, and our own fields merged in.
• Headers are logged by default: the request serializer pino-http uses, from pino-std-serializers, includes every request header, so Authorization and Cookie values reach the logs unless redact paths cover them.
• Request IDs without passing a logger around: Node.js AsyncLocalStorage plus Pino's mixin option adds a requestId to every line written during a request; nestjs-pino does the same for NestJS.
• Errors go first: since Pino v6, logger.error('failed', err) discards err entirely, while logger.error({ err }, 'failed') keeps the error type, message and stack.
• Pretty output is a development tool: production processes write JSON to stdout and the platform ships it; pino-pretty runs only locally.
What does structured logging give us that console.log does not?
Structured logging gives every log line queryable fields, so 'all error lines for one request in the payments service' becomes a filter instead of a regex. A string such as 'Payment failed for order 123' carries the same facts, but a log backend cannot index the order ID inside it, and nothing ties the line to the request that produced it.
We compared three options before settling on Pino:
• console.log: free-text output, request IDs added by hand, no secret redaction, no bound context fields.
• NestJS 11 ConsoleLogger with json: true: one JSON object per line and levels through the logLevels option, but request IDs and redaction stay manual, and context is a single string.
• Pino 10 with pino-http or nestjs-pino: one JSON object per line, a request ID attached automatically per request, built-in redact paths, a level option driven by LOG_LEVEL, and child loggers with bound fields through logger.child().
NestJS 11's built-in ConsoleLogger with json: true is a reasonable choice for a small service. We chose Pino because it adds the two things we kept rebuilding by hand: per-request context and redaction.
How do we attach a request ID to every log line in Node.js?
We store the request ID in AsyncLocalStorage at the start of each request and return it from Pino's mixin function. AsyncLocalStorage, from node:async_hooks, keeps a value available across every await and callback that runs inside als.run(), so code deep in a repository layer can log with the shared logger and still get the right ID.
Our Express setup has three parts. A module creates new AsyncLocalStorage<{ requestId: string; userId?: string }>() and a Pino logger whose mixin returns a copy of the current store: mixin: () => ({ ...logContext.getStore() }). A middleware reads the incoming x-request-id header, accepts it only if it matches /^[\w-]{1,64}$/, otherwise generates one with randomUUID() from node:crypto, echoes it back in the x-request-id response header, and calls logContext.run({ requestId }, next). Every log call made while that request is handled then carries the same requestId.
Two details cost us time. First, Pino's documentation states that the object returned by mixin() is mutated by Pino, so returning the store itself lets a logging call write fields back into the request context; the spread copy prevents that. Second, an incoming x-request-id header is user input, so we accept it only when it matches a short, safe pattern. Echoing the ID in the response header means a bug report can include it, and middleware that runs after authentication can set userId on the store for every later line.
How do we set up Pino in NestJS without losing bootstrap logs?
In NestJS we use nestjs-pino, which wraps pino-http and keeps a request-scoped child logger in AsyncLocalStorage, so services get the request ID without any of the code above. The setup has three parts: the module, the bootstrap and injection.
In AppModule we import LoggerModule.forRoot({ pinoHttp: { ... } }) with five options: level from LOG_LEVEL; a genReqId(req, res) function that reuses a valid incoming x-request-id or generates a UUID and sets it on the response; redact paths for req.headers.authorization, req.headers.cookie and res.headers["set-cookie"]; autoLogging: { ignore: (req) => req.url === '/health' }; and a pino-pretty transport only outside production.
In main.ts we create the app with NestFactory.create(AppModule, { bufferLogs: true }) and then call app.useLogger(app.get(Logger)), importing Logger from nestjs-pino. bufferLogs: true holds the logs NestJS writes while the module graph is built and flushes them through Pino once useLogger() runs; without it, the startup lines come out in Nest's default text format and the rest in JSON.
pino-http's genReqId becomes the req.id on every line, and autoLogging.ignore keeps health-check probes from writing a 'request completed' line every few seconds.
In services we inject PinoLogger with @InjectPinoLogger(PaymentsService.name) and always log an object first, for example this.logger.info({ orderId }, 'capturing payment'). To add a field to every remaining line of the current request, such as the user ID after a guard authenticates, nestjs-pino exposes PinoLogger.assign({ userId }).
Why do bearer tokens and cookies show up in logs?
Bearer tokens and session cookies show up in logs because pino-http serializes the incoming request with pino-std-serializers, and that serializer includes the full headers object. The response serializer includes the headers from res.getHeaders(), which carries set-cookie. Nothing is hidden until it is listed in Pino's redact option, so the first thing we check in any new pino-http setup is a single request line.
The rules we follow for redact paths:
• Paths are case-sensitive, and Node.js lowercases incoming header names, so the path is req.headers.authorization, not req.headers.Authorization.
• Header names with hyphens need bracket notation, as in res.headers["set-cookie"].
• The default censor value is [Redacted]; redact: { paths, remove: true } drops the key entirely instead.
• Pino's documentation notes that wildcard paths cost more than explicit ones and that redact paths must never come from user input, so we list explicit paths for the shapes we log.
• pino-http does not log request bodies by default, so body fields such as password only leak when our own code logs a whole DTO. We log specific fields instead.
Redaction only protects the paths someone remembered, so we test it. A small node:test case creates a Pino logger with our shared REDACT_PATHS list and an in-memory Writable stream as the destination, logs a fake request whose authorization header is 'Bearer test-secret-123', and asserts that the output never contains test-secret-123 and does contain [Redacted].
Why does Pino drop an error's stack trace?
Pino drops the error when it is passed after the message, because since Pino v6 extra arguments are only used to fill printf-style placeholders such as %s. logger.error('payment capture failed', err) writes the message and silently discards err: no type, no message, no stack.
The fix is argument order. logger.error({ err, orderId }, 'payment capture failed') sends err through Pino's default err serializer, pino.stdSerializers.err, which outputs the error's type, message and stack. logger.error(err) on its own also works: Pino wraps an Error passed as the first argument in { err } and uses err.message as the msg.
We look for .error(' followed by a comma and a variable during code review. It is a common mistake in code that moved over from console.error, which prints every argument it receives.
Should we use pino-pretty or a transport in production?
No. In production we write plain JSON to stdout and let the platform collect it: Docker's logging driver, Vercel's runtime logs, or an OpenTelemetry collector. pino-pretty, the formatter that turns Pino's JSON into coloured text, is for local development only, because log backends cannot parse its output.
When logs must go elsewhere, pino.transport() runs the transport in a worker thread, off the main event loop. We still prefer stdout plus a collector: an in-process transport is one more thing to flush during shutdown.
Level control is the other production setting. Pino replaces the methods for disabled levels with a no-op, so logger.debug() at level info costs almost nothing, but its arguments are still evaluated. For an expensive debug payload we guard the call with logger.isLevelEnabled('debug'). Setting LOG_LEVEL=debug on one instance during an incident gives us detail without a code change.
FAQ
Q: Is console.log good enough for production Node.js logs?
A: For scripts and small single-purpose services, often yes, especially with NestJS 11's ConsoleLogger in json: true mode. Once a service needs per-request correlation or secret redaction, a structured logger such as Pino pays for itself.
Q: Should we log request and response bodies with pino-http?
A: Not by default. pino-http's standard request serializer leaves bodies out, and adding them means every password, token and personal field in a payload needs its own redact path. We log the specific fields we need, such as an order ID.
Q: How do we correlate Pino logs with OpenTelemetry traces?
A: We add the active span's trace_id and span_id to each line, either with @opentelemetry/instrumentation-pino or by reading trace.getSpan(context.active()) inside a mixin. With a request ID and a trace ID on every line, we can jump from a slow trace to its logs.
Q: Which header should carry the request ID?
A: x-request-id is the common convention, and many proxies and load balancers already set or forward it. Accept an incoming value only after validating its length and characters, and generate a UUID otherwise.
Further Reading
Backend Engineering
Explicit Resource Management in TypeScript and Node.js 24: How We Use using, await using and DisposableStack
Connection leaks usually come from one error path that skipped a release() call. Node.js 24 runs using and await using natively, and TypeScript has compiled them since 5.2. Here is how our team makes database clients, transactions, temp directories and test fixtures disposable, when we use DisposableStack, and the two traps to avoid: SuppressedError and streams that outlive their scope.
Backend Engineering
Reading PostgreSQL EXPLAIN ANALYZE: How We Find the Missing Index Behind a Slow Node.js Endpoint
We stopped adding PostgreSQL indexes by guesswork. Our process: find the costliest query in pg_stat_statements, read its EXPLAIN (ANALYZE, BUFFERS) plan for rows that are read and thrown away, and add the one composite, partial or covering index the plan asks for, built with CREATE INDEX CONCURRENTLY.