SkillByAIOpen interactive version →

Lesson 22 / 32

Logging

Use Pino structured logging in Fastify with request-scoped loggers and meaningful log levels.

Pino: fast structured logging

Fastify comes with Pino, a high-performance JSON logger. Access it via fastify.log in routes and plugins.

Logging with context

Log with structured data for better debugging and monitoring.

fastify.get('/users/:id', async (req, reply) => {
  fastify.log.info({
    userId: req.params.id,
    method: req.method,
    timestamp: new Date().toISOString(),
  }, 'Fetching user');
  
  try {
    const user = await findUser(req.params.id);
    return user;
  } catch (err) {
    fastify.log.error({
      userId: req.params.id,
      error: err.message,
    }, 'Failed to fetch user');
    throw err;
  }
});

Quick check

Quick check: How do you turn on the built-in Pino logger?

  • `Fastify({ logger: true })`
  • `npm i pino` only
  • It is always on
Answer

`Fastify({ logger: true })` — Logging is off by default; `logger: true` enables Pino with per-request ids.