Skip to main content

Data and monitoring · Intermediate · 22 min

Write structured logs in Node.js with Pino

By Padding · Updated 18 Nov 2026
Node.js 26.13 · Pino 10.4.0 · pino-http 11.0.0 · Express 5.3.0 (node:26 image)

You will have an Express 5 API that writes one JSON log line per event with Pino 10.4, with levels, request ids on every line, redacted secrets, errors logged with their stack and readable output in development only.

On this page

console.log('user signed in', user) is fine while you watch one terminal. On a server with a few hundred requests a minute, you want to ask questions of your logs: show every error in the last hour, show everything that happened during request support-ticket-118, count warnings by route. Plain sentences cannot answer those. A JSON object per line can, because every fact sits in a named field that a log tool, or jq on your laptop, can filter.

Pino is a fast JSON logger for Node.js, and pino-http is its request logger for Express and the plain http module. In this tutorial you build a small orders API and give it logging you could run in production:

  • levels, so you can turn detail up and down without editing code
  • child loggers that stamp a request id and other context on every line
  • redaction, so tokens, cookies and passwords never reach the log
  • errors logged with their type, message and stack
  • pretty, coloured output while you develop, and plain JSON everywhere else
  • logs written to stdout, where the platform you deploy on collects them

You will check every result with jq, a command-line JSON processor.

Step 1 · Create the project and install Pino

Install jq and curl first. On Ubuntu:

Bash
sudo apt update
sudo apt install -y jq curl

On macOS, brew install jq does the same; curl is already there.

Make a throwaway project, switch it to ES modules and install the packages. The ~ ranges allow patch releases only, so a new minor version cannot change behaviour under you. pino-pretty is a development dependency because only your own machine needs it:

Bash
mkdir -p ~/pino-logs-demo/src
cd ~/pino-logs-demo
npm init -y
npm pkg set type=module
npm install pino@~10.4.0 pino-http@~11.0.0 express@~5.3.0
npm install --save-dev pino-pretty@~13.2.0

Check it worked

Bash
npm ls --depth=0

The list shows express@5.3.0, pino-http@11.0.0, pino-pretty@13.2.0 and pino@10.4.0, or later patch releases of each.

Step 2 · Write a logger and log at different levels

Every file in the app imports one shared logger, so its settings live in one place. Create src/logger.js:

Bash
cat > src/logger.js <<'JS'
import pino from 'pino'

export const logger = pino({
  level: process.env.LOG_LEVEL ?? 'info',
  base: { service: 'orders-api' },
  timestamp: pino.stdTimeFunctions.isoTime,
})
JS

Three choices are made here:

  • level comes from the LOG_LEVEL environment variable, so you can turn on debug output on one server without a code change. Anything below the level is skipped before it is formatted, which keeps disabled debug lines almost free.
  • base sets the fields Pino puts on every line. By default that is the process id and host name. Replacing them with the service name makes lines from several services easy to tell apart, and the platform you deploy on usually adds the host or container itself.
  • timestamp writes ISO 8601 times such as 2026-11-18T09:14:03.120Z instead of milliseconds since 1970, so you can read them at a glance.

Now a short script that logs at four levels. The first argument can be an object of fields, and the string after it becomes the msg field:

Bash
cat > src/try-logger.js <<'JS'
import { logger } from './logger.js'

logger.debug('cache warmed')
logger.info('service starting')
logger.info({ orderId: 'ord_1042', items: 3 }, 'order received')
logger.warn({ retryInMs: 500 }, 'payment provider slow')
JS
node src/try-logger.js

Each call writes one line of JSON. The levels, from least to most serious, are trace (10), debug (20), info (30), warn (40), error (50) and fatal (60). The number is what goes into the level field, which makes "warnings and worse" a simple level >= 40 filter.

Check it worked

The output is three lines, not four. The third reads something like this:

Text
{"level":30,"time":"2026-11-18T09:14:03.120Z","service":"orders-api","orderId":"ord_1042","items":3,"msg":"order received"}

The debug line is missing because the default level is info. Change the level and keep only the fields you care about with jq:

Bash
LOG_LEVEL=debug node src/try-logger.js | jq -c '{level, msg}'
LOG_LEVEL=warn node src/try-logger.js | jq -c '{level, msg}'

With debug you see four lines, starting with {"level":20,"msg":"cache warmed"}. With warn you see only {"level":40,"msg":"payment provider slow"}.

Step 3 · Add context with child loggers

Code deep inside a request rarely knows which order, user or request it is working for unless you pass that along. A child logger carries fields for you: you create it once with the context, and every line it writes includes those fields. Children can have children, and the fields add up.

Bash
cat > src/try-child.js <<'JS'
import { logger } from './logger.js'

const log = logger.child({ module: 'payments' })
log.info({ orderId: 'ord_1042' }, 'charging card')

const retry = log.child({ attempt: 2 })
retry.warn({ orderId: 'ord_1042' }, 'provider timed out, retrying')
JS
node src/try-child.js | jq -c '{module, attempt, orderId, msg}'

Pass the child to the functions that do the work, instead of importing the root logger in each one. In the HTTP steps later, pino-http does exactly this for you: it creates a child per request with the request id bound to it.

Check it worked

The first line has "module":"payments" and "attempt":null, because that field was not set yet. The second line has both "module":"payments" and "attempt":2, without the code repeating either.

Step 4 · Redact secrets before they are written

Once a password or token is in your logs, it is copied to every system the logs reach, kept for weeks and readable by everyone with log access. Pino can replace values at given paths before the line is written. Rewrite src/logger.js with a redact list:

Bash
cat > src/logger.js <<'JS'
import pino from 'pino'

export const logger = pino({
  level: process.env.LOG_LEVEL ?? 'info',
  base: { service: 'orders-api' },
  timestamp: pino.stdTimeFunctions.isoTime,
  redact: {
    paths: [
      'req.headers.authorization',
      'req.headers.cookie',
      'res.headers["set-cookie"]',
      'err.body',
      'password',
      '*.password',
    ],
    censor: '[Redacted]',
  },
})
JS

The first three paths cover the request and response headers that pino-http logs in the next step. err.body covers a detail that is easy to miss: when Express cannot parse a JSON body, the error it raises carries the raw body text, and that text can hold a password. password and *.password match a password field at the top level and one level down. A * wildcard matches exactly one level, not any depth.

Try it, including an object nested deeper than the wildcard reaches:

Bash
cat > src/try-redact.js <<'JS'
import { logger } from './logger.js'

logger.info({ user: { email: 'ada@example.com', password: 'hunter2' } }, 'signup received')
logger.info({ password: 'hunter2', step: 'login' }, 'login attempt')
logger.info({ form: { account: { password: 'hunter2' } } }, 'nested too deep')
JS
node src/try-redact.js | jq -c 'del(.time, .level, .service)'

Treat redaction as a safety net, not permission to log whole request bodies. The habit that protects users is to log the few fields you need (an order id, an item count) and never the body itself. Add paths for anything else your app handles that identifies a person. In many African markets a phone number is also the customer's mobile-money account, so a path such as *.phone belongs on the list next to passwords.

Check it worked

The first two lines show "password":"[Redacted]", with the email and step fields left alone. The third still shows hunter2, because form.account.password is two levels down. To cover it, list the full path form.account.password, or better, stop logging that object.

Step 5 · Log every request with pino-http

Now the API. Create src/app.js. pino-http is the first middleware, so it sees every request and logs one line when each response finishes:

Bash
cat > src/app.js <<'JS'
import { randomUUID } from 'node:crypto'
import express from 'express'
import { pinoHttp } from 'pino-http'
import { logger } from './logger.js'

const SAFE_ID = /^[A-Za-z0-9_-]{1,64}$/

const httpLogger = pinoHttp({
  logger,
  quietReqLogger: true,
  genReqId(req, res) {
    const incoming = req.headers['x-request-id']
    const id = typeof incoming === 'string' && SAFE_ID.test(incoming) ? incoming : randomUUID()
    res.setHeader('X-Request-Id', id)
    return id
  },
  customLogLevel(req, res, err) {
    if (err || res.statusCode >= 500) return 'error'
    if (res.statusCode >= 400) return 'warn'
    return 'info'
  },
})

export const app = express()
app.use(httpLogger)
app.use(express.json())

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok' })
})

app.post('/api/orders', (req, res) => {
  const log = req.log.child({ route: 'create-order' })
  const items = Array.isArray(req.body?.items) ? req.body.items : []
  log.info({ items: items.length }, 'creating order')
  if (items.length === 0) {
    log.warn('order has no items')
    return res.status(422).json({ error: 'Add at least one item', requestId: req.id })
  }
  log.info({ orderId: 'ord_1042' }, 'order saved')
  res.status(201).json({ id: 'ord_1042' })
})

app.get('/api/reports/daily', async () => {
  throw new Error('report store unavailable')
})

app.use((req, res) => {
  res.status(404).json({ error: 'Not found', requestId: req.id })
})

app.use((err, req, res, next) => {
  if (res.headersSent) return next(err)
  res.err = err
  const status = err.status ?? 500
  res.status(status).json({
    error: status < 500 ? 'Bad request' : 'Something went wrong',
    requestId: req.id,
  })
})
JS

What the pino-http options do:

  • logger reuses your logger, so the request lines get the same base fields, timestamps and redaction.
  • genReqId gives each request its id. If a caller, such as a proxy or another of your services, already sent an X-Request-Id, the same id is kept so one id follows the request across systems. The pattern check stops a caller from putting a 10 KB string or odd characters into your logs. The id also goes back in the response header, so a user who reports a problem can quote it.
  • quietReqLogger: true makes req.log a child that carries only reqId. Without it, every line your handlers write repeats the whole request object.
  • customLogLevel logs 4xx responses as warnings and 5xx responses as errors, so a level >= 50 filter finds the failures that are your fault.

Inside a handler, req.log is that per-request child logger. The orders route makes its own child from it to add route, as in the previous step. The last two handlers matter in the next step.

Create src/server.js, the only file that starts listening:

Bash
cat > src/server.js <<'JS'
import { app } from './app.js'
import { logger } from './logger.js'

const port = Number(process.env.PORT ?? 3000)

const server = app.listen(port, '127.0.0.1', (err) => {
  if (err) {
    logger.fatal({ err }, 'could not start server')
    process.exitCode = 1
    return
  }
  logger.info({ port }, 'listening')
})

process.on('SIGTERM', () => {
  logger.info('shutting down')
  server.close()
})
JS

Process managers and container platforms stop a service with SIGTERM. Logging it means a restart shows up in the logs as a clean stop, not a mysterious gap.

Start the server in your second terminal. tee shows the lines and also saves a copy in server.log, so you can query them in a moment:

Bash
cd ~/pino-logs-demo
node src/server.js | tee server.log

In your first terminal, send three requests. The token is a made-up value to show that it never reaches the log:

Bash
cd ~/pino-logs-demo
curl -s -w '\n' -H 'Authorization: Bearer demo-token-123' http://127.0.0.1:3000/api/health
curl -s -i -H 'X-Request-Id: support-ticket-118' --json '{"items": ["tea", "bread"]}' http://127.0.0.1:3000/api/orders
curl -s -w '\n' --json '{"items": []}' http://127.0.0.1:3000/api/orders

The replies are {"status":"ok"}, then the headers and body of a 201 Created with X-Request-Id: support-ticket-118, then a 422 body with Add at least one item and a generated requestId.

Check it worked

Pull every line for one request out of the log, and look at what happened to the token:

Bash
sleep 1
jq -c 'select(.reqId == "support-ticket-118") | {level, msg, route, status: .res.statusCode}' server.log
jq -r 'select(.req.headers.authorization) | .req.headers.authorization' server.log

The first command prints three lines for that request: creating order and order saved with "route":"create-order", then pino-http's request completed with "status":201. The second prints [Redacted]. For the empty order, order has no items and the request completed line for the 422 have level 40; creating order stays at 30.

Step 6 · Log errors with their stack

An error log line is only useful if it says what failed and where. Pino has a serializer for errors that writes type, message, stack and any extra properties such as code, but it applies only to a field named err. Two common mistakes lose that information, and the script below makes both on purpose:

Bash
cat > src/try-errors.js <<'JS'
import { readFileSync } from 'node:fs'
import { logger } from './logger.js'

try {
  readFileSync('settings.json', 'utf8')
} catch (err) {
  logger.error({ err, file: 'settings.json' }, 'could not read settings')
  logger.error({ error: err }, 'wrong key')
  logger.error('wrong argument order', err)
}
JS
node src/try-errors.js | jq -c '{msg, type: .err.type, code: .err.code, error}'

settings.json does not exist, so readFileSync throws. The first call is the right form: the error goes in as err, next to any other fields, with the message after.

The other two calls show what goes wrong. Under any other key, such as error, the error is logged like a plain object. A JavaScript error's message and stack are not ordinary enumerable properties, so they vanish and only extras such as code survive. When the message comes first, Pino treats later arguments as values for %s-style placeholders in the message. With no placeholder, the error is dropped completely.

In the app, errors reach the log through the error handler you wrote in src/app.js. Express 5 passes the rejected promise from the async /api/reports/daily handler to it. The handler sets res.err = err, and pino-http logs the request with that error when the response finishes. Without that line, pino-http still marks a 500 as failed, but with a generic failed with status code 500 error and not your stack. The client gets a short message and the request id, never the stack.

Trigger a server error, then send a body that is not valid JSON:

Bash
curl -s -w '\n' http://127.0.0.1:3000/api/reports/daily
curl -s -w '\n' --json '{"password": "hunter2"' http://127.0.0.1:3000/api/orders

The replies are {"error":"Something went wrong","requestId":"..."} and {"error":"Bad request","requestId":"..."}.

Check it worked

The script's output shows the three cases side by side. The first line has "type":"Error","code":"ENOENT". The second has "error" holding only errno, code, syscall and path, with no message or stack. The third has no error information at all.

Then look at the failed requests in the server log:

Bash
sleep 1
jq -c 'select(.err) | {level, status: .res.statusCode, message: .err.message, body: .err.body}' server.log
jq -r 'select(.err.message == "report store unavailable") | .err.stack' server.log | head -n 2

The first command prints two lines: level 50 with status 500 and report store unavailable, then level 40 with status 400, the JSON parse error message and "body":"[Redacted]". The second prints the first two lines of the stack, starting with Error: report store unavailable and then a line like at file:///root/pino-logs-demo/src/app.js:45:9, which points at the throw. Your path shows your own home folder.

Step 7 · Make logs readable in development

JSON lines are easy for tools and tiring for eyes. pino-pretty turns them into coloured, indented text. Keep it out of the app itself: the app always writes JSON, and in development you pipe that JSON through pino-pretty. Production never loads it, and a deploy with npm ci --omit=dev does not even install it.

Add the scripts:

Bash
npm pkg set scripts.start="node src/server.js"
npm pkg set scripts.dev="node --watch src/server.js | pino-pretty"

npm start is what a server runs. npm run dev restarts on every save and prints pretty output. Try pino-pretty on the lines you already have:

Bash
head -n 2 server.log | npx pino-pretty --colorize false

To see the dev script, run it on another port in a third terminal while the first server keeps running, send a request to it, then stop it with Ctrl+C:

Bash
cd ~/pino-logs-demo
PORT=3001 npm run dev

Check it worked

The head command prints something like this, with the time in your local time zone:

Text
[09:14:03.120] INFO: listening
    service: "orders-api"
    port: 3000
[09:14:04.551] INFO: request completed
    service: "orders-api"
    reqId: "..."

The dev server prints the same layout, in colour, starting with INFO: listening and port: 3001. npm pkg get scripts.start prints "node src/server.js", with no pino-pretty in sight.

Step 8 · Log to stdout and let the platform collect it

The app never opens a log file. Pino writes to standard output, and whatever runs the process decides where the lines go. That is the same app on every platform:

  • Docker and Kubernetes capture each container's stdout. docker logs <container> shows it, and a log agent ships it on.
  • systemd sends a service's stdout to the journal. journalctl -u <service> -o cat prints the raw lines, ready for jq.
  • A log collector such as Grafana Alloy reads those same streams and sends them to a log store you can search.

Writing your own files instead brings jobs the app should not own: rotating them before the disk fills, deleting old ones, keeping file permissions safe, and losing lines when a container is replaced and its disk goes with it. Pino's own documentation recommends logging to stdout and doing any processing in a separate thread or process, so a slow log destination never slows your requests down. If a legacy server really must keep files, let the process manager redirect stdout to a file and rotate it with logrotate, still outside the app.

Because every line is JSON, server.log already answers questions. Show everything at warning level or worse, then count lines by level:

Bash
jq -c 'select(.level >= 40) | {time, level, msg, url: .req.url}' server.log
jq -s -c 'group_by(.level) | map({level: .[0].level, lines: length})' server.log
jq -e . server.log > /dev/null && echo "every line is JSON"

The same filters work on docker logs or journalctl -o cat output, and the field names become search terms in a log store.

When you have finished, stop the server with Ctrl+C in the second terminal, then remove the demo project. Node.js and jq stay installed:

Bash
cd ~
rm -rf ~/pino-logs-demo

Check it worked

Before the cleanup, the first jq command listed the warnings and errors from the earlier steps. pino-http's own lines, such as request completed for the 422 and request errored for the 500, show the URL. The handler's order has no items warning shows "url":null, because req.log carries only reqId, not the request. The second printed something like [{"level":30,"lines":8},{"level":40,"lines":3},{"level":50,"lines":1}]; your counts depend on how many requests you sent. The third printed every line is JSON. After the cleanup, ls ~/pino-logs-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.