Lesson 20 / 30

Logging

Use Pino (Fastify's built-in logger) for structured logging.

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;
  }
});