Skip to content
jshacks.dev
Node.js

How to Log Properly in Node.js With pino

Set up structured JSON logging in Node.js with pino: log levels, child loggers, redacting secrets, serialising errors and pretty output for development.

7 min read
Summarize in AI
Flat illustration of a magnifier over lines of a log, with the Node.js, TypeScript, npm and JavaScript logos.

console.log is fine for a script and wrong for a service. It has no levels, so you cannot silence debug noise in production. It writes free-form text, so a log aggregator cannot filter by user or request. And heavy logging through it competes with the code that is doing the real work. pino fixes those problems with a small, fast logger that writes one JSON object per line. This post shows how to set it up properly: levels, context with child loggers, error logging, redacting secrets, readable output in development and the mistakes to avoid. The samples use ES modules on Node.js 26 and pino installed with npm install pino.

Why structured logs

A line like User 42 failed to pay invoice 1042 is readable by a person and opaque to a tool. To find every payment failure for one user you would write a regular expression and hope the wording never changes. A structured log keeps the facts as fields.

Text
{"level":"error","userId":42,"invoiceId":1042,"msg":"payment failed"}

Now userId is a field a log system can index and filter on, and the message stays a short constant string you can group by. That is the whole idea: constant message, variable data in fields. When you catch yourself building a message with a template literal, move the variable parts into the object instead.

The smallest setup

logger.jsJavaScript
import pino from "pino";

export const logger = pino({
  base: null,
  timestamp: false,
});

logger.info("server started");
logger.warn({ port: 3000 }, "port was busy, using another");
Text
{"level":30,"msg":"server started"}
{"level":40,"port":3000,"msg":"port was busy, using another"}

Two things are worth noticing. The argument order is an object of fields first and the message second, which is the reverse of what many people expect. And the sample turns off two defaults so the output is fixed. By default pino adds time as epoch milliseconds, plus pid and hostname, so a real line looks like {"level":30,"time":1767225600000,"pid":4821,"hostname":"web-1","msg":"server started"}. Those fields are useful in production, so leave base and timestamp alone there. The values differ on every machine and run.

Levels

pino has six levels, each with a number: trace 10, debug 20, info 30, warn 40, error 50 and fatal 60. A logger has a minimum level, and anything below it is dropped before it is formatted, which is part of why pino is fast. The default minimum is info. Read raw output by the numbers: 30 is info, 40 is warn, 50 is error.

Set the level from the environment so production and development can differ without a code change.

level.jsJavaScript
import pino from "pino";

const logger = pino({
  level: process.env.LOG_LEVEL ?? "info",
  base: null,
  timestamp: false,
});

logger.debug("cache lookup for key user:42");
logger.info("request handled");
console.log("level is", logger.level);

With no LOG_LEVEL set:

Text
{"level":30,"msg":"request handled"}
level is info

The debug call produced nothing because info is the minimum. Run the same file with LOG_LEVEL=debug and both lines appear. A guard such as if (logger.isLevelEnabled("debug")) is worth using before building an expensive object only for a debug line.

Numbers are compact, but many log tools expect a label. The formatters option changes how the level is written.

labels.jsJavaScript
import pino from "pino";

const logger = pino({
  base: null,
  timestamp: false,
  formatters: {
    level: (label) => ({ level: label }),
  },
});

logger.error({ orderId: 9 }, "charge declined");
Text
{"level":"error","orderId":9,"msg":"charge declined"}

The formatter receives the label ("error") and returns the object to merge, so the field is now text. Pick one convention for the whole system and keep it, because mixing numeric and text levels across services makes queries awkward.

Child loggers carry context

The most useful pino feature is the child logger. It inherits everything from its parent and adds fields that appear on every line it writes. Create one per request, per job or per connection.

child.jsJavaScript
import pino from "pino";

const logger = pino({ base: null, timestamp: false });

const reqLogger = logger.child({ reqId: "r-7f3a", userId: 42 });

reqLogger.info("request started");
reqLogger.info({ ms: 18 }, "request finished");
Text
{"level":30,"reqId":"r-7f3a","userId":42,"msg":"request started"}
{"level":30,"reqId":"r-7f3a","userId":42,"ms":18,"msg":"request finished"}

The reqId and userId fields were written once, when the child was created, and appear on both lines. Searching your log system for r-7f3a now returns the whole story of one request. Passing that logger down through your functions is the simple approach. If threading it through every call is painful, How to Add Request IDs With AsyncLocalStorage shows how to make the right logger available anywhere in a request without passing it.

Log errors so the stack survives

Passing an error as the first argument or under the err key makes pino serialise it into fields: the class name, the message and the stack.

errors.jsJavaScript
import pino from "pino";

const logger = pino({ base: null, timestamp: false });

try {
  JSON.parse("{not json");
} catch (err) {
  logger.error({ err }, "could not parse payload");
}
Text
{"level":50,"err":{"type":"SyntaxError","message":"Expected property name or '}' in JSON at position 1 (line 1 column 2)","stack":"SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)\n    at JSON.parse (<anonymous>)\n    at file:///srv/app/errors.js:6:8"},"msg":"could not parse payload"}

The stack string contains paths and line numbers from your machine, and the message text comes from the V8 version in use, so yours will differ in those details. The important part is the key name. The default serialiser is attached to err, so { err } works and { error } or { e } does not: those would print as an empty object because an Error has no enumerable own properties. Name the key err every time.

Redact secrets

A log line is a copy of your data that lives far longer than the request, and it is often read by more people than the database is. Never log passwords, tokens or card numbers. Use redact as a safety net for the case where someone logs a whole object by accident.

redact.jsJavaScript
import pino from "pino";

const logger = pino({
  base: null,
  timestamp: false,
  redact: ["password", "req.headers.authorization"],
});

logger.info(
  {
    password: "hunter2",
    req: { method: "POST", headers: { authorization: "Bearer abc123" } },
  },
  "login attempt",
);
Text
{"level":30,"password":"[Redacted]","req":{"method":"POST","headers":{"authorization":"[Redacted]"}},"msg":"login attempt"}

Each entry in redact is a path into the logged object. Matching values are replaced with the string [Redacted], and you can change that with the object form of the option, using censor or remove: true to delete the key. Redaction works only on paths you list. It cannot know that a field called note happens to contain a token, so treat it as a second line of defence behind not logging secrets in the first place.

Pretty output in development

JSON is for machines. In development you want readable colour output, and pino keeps that out of the main package: the logger always writes JSON, and a separate tool formats it. Install pino-pretty as a development dependency and use it as a transport.

dev-logger.jsJavaScript
import pino from "pino";

const isDev = process.env.NODE_ENV !== "production";

export const logger = pino({
  level: process.env.LOG_LEVEL ?? "info",
  transport: isDev
    ? { target: "pino-pretty", options: { colorize: true } }
    : undefined,
});

A transport runs in a worker thread, so formatting work stays off your main thread. In production leave transport undefined and write JSON to stdout, then let the platform collect it. Do not ship pino-pretty to production: it costs CPU and it destroys the machine-readable format your aggregator expects. You can also pipe instead, with node server.js | npx pino-pretty, which formats the output without touching the code.

Log to stdout and let the platform ship it

A twelve-factor style service writes logs to stdout and does not manage files itself. Containers, systemd and platform runtimes all capture stdout and handle rotation and shipping. If you must write to a file, give pino a destination.

file-logger.jsJavaScript
import pino from "pino";

const logger = pino(
  { base: null, timestamp: false },
  pino.destination({ dest: "/var/log/app/app.log", sync: false }),
);

logger.info("written to a file");

With sync: false pino buffers writes and flushes them asynchronously, which is faster and has a trade-off: if the process crashes hard, the last buffered lines can be lost. Flush the destination in a shutdown handler, or keep the default synchronous destination when losing a final line is unacceptable. The pino documentation on asynchronous logging explains the details.

An HTTP request logger

You rarely write per-request logging by hand. The pino-http package adds a logger to each request and logs a line when the response finishes, with the method, URL, status and response time. It also gives every request a child logger on req.log, so the context pattern above comes for free. Start with the defaults and tune what it records, because by default it logs request headers that can include credentials, which is another reason to configure redact.

What to avoid

  • Logging inside a hot loop. Even a fast logger has a cost. Log summaries, not every iteration.

  • Building messages with templates. A message built from a template literal, such as "user 42 logged in", defeats grouping. Use { userId: id } and a constant message.

  • **Using console.log next to pino.** It bypasses levels, redaction and formatting. Replace it, or at least route it through the logger.

  • Logging whole request bodies. They contain personal data and secrets. Log the ids and sizes you need.

  • Creating a new logger per call. Create one at startup and derive children from it.

Share

Keep reading

Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, RabbitMQ, Apache Kafka, Redis and npm logos.
Node.js

What Is Node.js, and What Is It Good At?

Node.js runs JavaScript outside the browser on the V8 engine. Learn what it is, how its event loop works, where it shines, and where another tool fits better.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.