Node.js7 min read
Logging with Winston
Implement proper logging with Winston. Learn log levels and rotation.
Michael Torres
December 19, 2025
0.0k0
Logging with Winston
Why Logging?
- Debug production issues
- Track errors
- Monitor performance
- Audit user actions
Setup
npm install winston
Basic Logger
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
logger.info('User logged in', { userId: 123 });
logger.error('Payment failed', { error: err.message });
Log Levels
logger.error('Critical error');
logger.warn('Warning message');
logger.info('Info message');
logger.http('HTTP request');
logger.debug('Debug info');
Request Logging
const morgan = require('morgan');
app.use(morgan('combined', {
stream: {
write: (message) => logger.http(message.trim())
}
}));
Error Logging
process.on('uncaughtException', (error) => {
logger.error('Uncaught Exception', { error: error.stack });
process.exit(1);
});
app.use((err, req, res, next) => {
logger.error('Express error', {
error: err.message,
stack: err.stack,
url: req.url
});
res.status(500).json({ error: 'Internal server error' });
});
Key Takeaway
Use Winston for structured logging. Log to files in production. Include context in logs. Monitor error logs. Never log sensitive data.
#Node.js#Logging#Winston#Monitoring