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