Logging
Sixteenth chapter of the "Fastify with TypeScript" series. Good logging is essential for understanding what's happening in production. Fastify natively integrates Pino, one of the fastest JSON loggers in the Node.js ecosystem, and we switched it on back in chapter 4. Let's look at what it has been writing all along, and make three improvements.
What you already have
Start the server, create a user with the curl command from chapter 13, and read the terminal. Every request produces at least two lines:
{"level":30,"time":1795538650083,"pid":2091,"hostname":"vm","reqId":"req-1","req":{"method":"POST","url":"/api/v1/users","host":"localhost:3000","remoteAddress":"127.0.0.1","remotePort":45864},"msg":"incoming request"}
{"level":30,"time":1795538650144,"pid":2091,"hostname":"vm","reqId":"req-1","res":{"statusCode":201},"responseTime":60.142908000000034,"msg":"request completed"}
Three things are worth pointing out:
- Each line is one JSON object. A log collector (Loki, Datadog, CloudWatch) can filter on any field without parsing text: all requests slower than 500 ms, all
5xx, everything from one address. -
reqIdis the same on both lines. Fastify gives every request an id and attaches it to everything logged during that request, so you can pull out the full story of one request from a busy log. -
levelis a number: 30 isinfo, 40warn, 50error. The minimum level written comes fromLOG_LEVELin our config. Useinfoin production and setLOG_LEVEL=debugin your.envwhen you need more detail locally.
The error handler from chapter 10 already uses levels deliberately: a 5xx is logged as an error with its stack trace, a 4xx as a single info line.
Logging your own events
Inside a handler, use request.log, which carries the request id. In src/users/users.route.ts, add a line to the POST handler, right after the user is created:
const user = await users.create(request.body);
request.log.info({ userId: user.id }, 'User created');
{"level":30,"time":1795538650137,"pid":2091,"hostname":"vm","reqId":"req-1","userId":"5030c153-c1e4-4550-ae1d-a8b037984cbe","msg":"User created"}
Pass the data as an object first, the message second. String interpolation (log.info(`user ${id} created`)) throws away the structure that makes JSON logs searchable: with the object form you can ask for every line where userId equals a given value.
Log the events that matter to the business (a user signed up, a payment failed), not every step of the code. Outside a request, use fastify.log in plugins and this.log in hooks.
Keeping secrets out of the log
Logs are copied to more places, and read by more people, than your database. A password or a token must never end up in one. Rather than trusting every developer to remember, tell the logger. In src/app.ts, replace the logger option:
logger: {
level: config.LOG_LEVEL,
// Replaced with [Redacted] before a line is written, wherever they appear
redact: ['req.headers.authorization', '*.password', '*.password_hash'],
},
To see it work, add a careless line at the top of the POST handler, the kind that gets written during a debugging session and forgotten:
request.log.info({ body: request.body }, 'Creating user');
{"level":30,"time":1795538650089,"pid":2091,"hostname":"vm","reqId":"req-1","body":{"name":"Ada","email":"ada@example.com","password":"[Redacted]"},"msg":"Creating user"}
The password never reached the log. Remove the careless line anyway: redaction is a safety net, not a reason to log request bodies.
Request ids across services
If a load balancer or another service in front of yours already assigns a request id, reuse it, so the same id appears in every system the request went through:
const app = Fastify({
requestIdHeader: 'x-request-id',
logger: { /* ... */ },
});
With this option, a request arriving with x-request-id: abc-123 is logged with "reqId":"abc-123" instead of req-1.
Pretty output in development
Production wants raw JSON. Humans don't. Pipe the output through pino-pretty, in development only:
npm install -D pino-pretty
and change the dev script in package.json:
"dev": "node --watch --env-file-if-exists=.env src/server.ts | pino-pretty"
[16:44:42.020] INFO (2206): incoming request
reqId: "req-1"
req: {
"method": "GET",
"url": "/health",
"host": "localhost:3000",
"remoteAddress": "127.0.0.1",
"remotePort": 53824
}
[16:44:42.026] INFO (2206): request completed
The pretty-printer is a separate process that reformats what the application writes. The application itself logs the same JSON in every environment, and npm start is untouched.
Custom serializers
If some object appears in many log lines, define once how it is rendered:
logger: {
serializers: {
user: (user: { id: string; email: string }) => ({ id: user.id }),
},
}
Now request.log.info({ user }, 'Looking up user') writes only "user":{"id":"42"}, even when someone passes the whole database row.
⬅️ Previous chapter: Testing · ➡️ Next chapter: Performance
This article is part of the "Fastify with TypeScript" series — chapter 16 of 18.
Top comments (0)