Topics Production Fastify Logging & Monitoring
intermediate 14 min read

Logging & Monitoring

Configure structured logging, health checks, and monitoring for Fastify services.

Structured Logging

const Fastify = require('fastify');\n\n// Pino logger configuration\nconst app = Fastify({\n  logger: {\n    level: process.env.LOG_LEVEL || 'info',\n    transport: {\n      target: 'pino-pretty',\n      options: {\n        colorize: true,\n        translateTime: 'HH:MM:ss.l',\n        ignore: 'pid,hostname',\n      },\n    },\n    serializers: {\n      req: (req) => ({\n        method: req.method,\n        url: req.url,\n        headers: { host: req.headers.host, 'user-agent': req.headers['user-agent'] },\n      }),\n      res: (res) => ({\n        statusCode: res.statusCode,\n      }),\n    },\n  },\n});\n\n// Custom log levels\napp.log.trace('Trace message');\napp.log.debug('Debug message');\napp.log.info('Info message');\napp.log.warn('Warning message');\napp.log.error('Error message');\napp.log.fatal('Fatal message');\n\n// Request-specific logging\napp.addHook('onRequest', async (request) => {\n  request.log.info({ url: request.url }, 'Incoming request');\n});

Health Checks

// @fastify/under-pressure for health monitoring\nawait app.register(require('@fastify/under-pressure'), {\n  maxEventLoopDelay: 1000,\n  maxHeapUsedBytes: 500 * 1024 * 1024,  // 500MB\n  maxRssBytes: 1000 * 1024 * 1024,       // 1GB\n  maxEventLoopUtilization: 0.98,\n  pressureHandler: (req, reply, type, value) => {\n    reply.code(503).send({ error: 'Service under pressure' });\n  },\n});\n\n// Custom health endpoint\napp.get('/health', async (request, reply) => {\n  const memory = process.memoryUsage();\n  \n  return {\n    status: 'healthy',\n    version: process.env.APP_VERSION || '1.0.0',\n    uptime: process.uptime(),\n    memory: {\n      heapUsed: `${Math.round(memory.heapUsed / 1024 / 1024)}MB`,\n      heapTotal: `${Math.round(memory.heapTotal / 1024 / 1024)}MB`,\n      rss: `${Math.round(memory.rss / 1024 / 1024)}MB`,\n    },\n    timestamp: new Date().toISOString(),\n  };\n});

Examples

const Fastify = require('fastify');

const app = Fastify({
  logger: {
    level: 'info',
    transport: {
      target: 'pino-pretty',
      options: { colorize: true },
    },
  },
});

// Health check endpoint
app.get('/health', async () => {
  const mem = process.memoryUsage();
  return {
    status: 'ok',
    uptime: process.uptime(),
    memory: {
      heap: `\${"$"}{Math.round(mem.heapUsed / 1024 / 1024)}MB`,
      rss: `\${"$"}{Math.round(mem.rss / 1024 / 1024)}MB`,
    },
    pid: process.pid,
    timestamp: new Date().toISOString(),
  };
});

// Graceful shutdown
const start = async () => {
  await app.listen({ port: 3000 });
  app.log.info('Server started');

  const signals = ['SIGINT', 'SIGTERM'];
  for (const signal of signals) {
    process.on(signal, async () => {
      app.log.info(`Received \${"$"}{signal}, shutting down`);
      await app.close();
      process.exit(0);
    });
  }
};

start();

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.