Databases, Testing, and DeploymentLesson 6.4
Logging and monitoring Node.js applications in production
winston setup, log levels, structured JSON logging, morgan integration, correlation IDs, error logging, health check endpoints
console.log Is Not Production Logging
Production logs need levels (error/warn/info/debug), structured JSON output for log aggregators, and multiple transports.
npm install winstonconst winston = require('winston');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' })
]
});
module.exports = logger;logger.info('Server started', { port: 3000 });
logger.error('DB connection failed', { error: err.message, stack: err.stack });Health Check Endpoint
app.get('/health', async (req, res) => {
const db = await checkDatabase().catch(() => false);
res.status(db ? 200 : 503).json({
status: db ? 'healthy' : 'degraded',
uptime: process.uptime(),
timestamp: new Date().toISOString()
});
});