Winston Logger - Quick Reference
When to Use This Skill
- Logging with multiple transports (file, console, HTTP)
- Structured logging with custom levels
- Automatic log file rotation
Deep Knowledge: Use mcp__documentation__fetch_docs with technology: winston for comprehensive documentation.
Basic Setup
npm install winston
Essential Patterns
Logger Base
import winston from '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' }),
],
});
// Add console in development
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple(),
}));
}
Custom Format
const customFormat = winston.format.printf(({ level, message, timestamp, ...meta }) => {
return `${timestamp} [${level.toUpperCase()}]: ${message} ${Object.keys(meta).length ? JSON.stringify(meta) : ''}`;
});
const logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(),
customFormat
),
transports: [new winston.transports.Console()],
});
Child Logger
const childLogger = logger.child({ requestId: req.id, module: 'auth' });
childLogger.info('User authenticated', { userId: user.id });
Daily Rotate File
import DailyRotateFile from 'winston-daily-rotate-file';
const transport = new DailyRotateFile({
filename: 'logs/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '20m',
maxFiles: '14d',
});
logger.add(transport);
When NOT to Use This Skill
- High-performance APIs: Use Pino instead - 10x faster than Winston
- JSON-only logging: Pino is more optimized for structured JSON output
- Serverless/Lambda: Prefer simpler console logging or Pino for lower overhead
- Python/Java projects: Use language-specific logging frameworks
- Simple scripts: Built-in console is sufficient for basic debugging
Anti-Patterns
| Anti-Pattern |
Why It's Bad |
Solution |
| Synchronous file logging |
Blocks event loop, degrades performance |
Use async transports with { stream: ... } |
| Logging objects without serialization |
Can log [Object] instead of data |
Use JSON.stringify() or Winston JSON format |
| No log rotation |
Disk fills up in production |
Use winston-daily-rotate-file |
| Logging in tight loops |
Overwhelms I/O, fills disks |
Add conditional logic or sample logs |
| String concatenation |
Always evaluated, even when disabled |
Use format strings: logger.info('User %s', userId) |
| Missing error stack traces |
Loses debugging context |
Use { error: err } or Winston error format |
Quick Troubleshooting
| Issue |
Cause |
Solution |
| Logs not appearing |
Wrong log level configured |
Check logger.level and transport levels |
| Performance degradation |
Synchronous file writes |
Use async transports or reduce log verbosity |
| Disk full |
No log rotation |
Configure winston-daily-rotate-file with maxFiles |
[Object] in logs |
Improper object formatting |
Use winston.format.json() or winston.format.prettyPrint() |
| Duplicate logs |
Multiple transports to same destination |
Review transport configuration |
| Colors not showing |
Console transport missing colorize |
Add winston.format.colorize() to console transport |
1---2name: winston3description: Winston - versatile logging library for Node.js with multiple transports, custom formatting, and log rotation. Supports structured logging, custom levels, and enterprise integration. USE WHEN: user mentions "winston", "node.js logging", "multiple transports", "log rotation", asks about "how to log to multiple destinations", "rotate log files in Node.js", "custom log formats" DO NOT USE FOR: Pino logging - use `pino` instead, Python logging - use `python-logging` instead, Java logging - use `slf4j` or `logback` instead4---5# Winston Logger - Quick Reference67## When to Use This Skill8- Logging with multiple transports (file, console, HTTP)9- Structured logging with custom levels10- Automatic log file rotation1112> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `winston` for comprehensive documentation.1314## Basic Setup1516```bash17npm install winston18```1920## Essential Patterns2122### Logger Base23```typescript24import winston from 'winston';2526const logger = winston.createLogger({27 level: 'info',28 format: winston.format.combine(29 winston.format.timestamp(),30 winston.format.json()31 ),32 transports: [33 new winston.transports.File({ filename: 'error.log', level: 'error' }),34 new winston.transports.File({ filename: 'combined.log' }),35 ],36});3738// Add console in development39if (process.env.NODE_ENV !== 'production') {40 logger.add(new winston.transports.Console({41 format: winston.format.simple(),42 }));43}44```4546### Custom Format47```typescript48const customFormat = winston.format.printf(({ level, message, timestamp, ...meta }) => {49 return `${timestamp} [${level.toUpperCase()}]: ${message} ${Object.keys(meta).length ? JSON.stringify(meta) : ''}`;50});5152const logger = winston.createLogger({53 format: winston.format.combine(54 winston.format.timestamp(),55 customFormat56 ),57 transports: [new winston.transports.Console()],58});59```6061### Child Logger62```typescript63const childLogger = logger.child({ requestId: req.id, module: 'auth' });64childLogger.info('User authenticated', { userId: user.id });65```6667### Daily Rotate File68```typescript69import DailyRotateFile from 'winston-daily-rotate-file';7071const transport = new DailyRotateFile({72 filename: 'logs/app-%DATE%.log',73 datePattern: 'YYYY-MM-DD',74 maxSize: '20m',75 maxFiles: '14d',76});7778logger.add(transport);79```8081## When NOT to Use This Skill8283- **High-performance APIs**: Use Pino instead - 10x faster than Winston84- **JSON-only logging**: Pino is more optimized for structured JSON output85- **Serverless/Lambda**: Prefer simpler console logging or Pino for lower overhead86- **Python/Java projects**: Use language-specific logging frameworks87- **Simple scripts**: Built-in console is sufficient for basic debugging8889## Anti-Patterns9091| Anti-Pattern | Why It's Bad | Solution |92|--------------|--------------|----------|93| Synchronous file logging | Blocks event loop, degrades performance | Use async transports with `{ stream: ... }` |94| Logging objects without serialization | Can log `[Object]` instead of data | Use `JSON.stringify()` or Winston JSON format |95| No log rotation | Disk fills up in production | Use `winston-daily-rotate-file` |96| Logging in tight loops | Overwhelms I/O, fills disks | Add conditional logic or sample logs |97| String concatenation | Always evaluated, even when disabled | Use format strings: `logger.info('User %s', userId)` |98| Missing error stack traces | Loses debugging context | Use `{ error: err }` or Winston error format |99100## Quick Troubleshooting101102| Issue | Cause | Solution |103|-------|-------|----------|104| Logs not appearing | Wrong log level configured | Check `logger.level` and transport levels |105| Performance degradation | Synchronous file writes | Use async transports or reduce log verbosity |106| Disk full | No log rotation | Configure `winston-daily-rotate-file` with `maxFiles` |107| `[Object]` in logs | Improper object formatting | Use `winston.format.json()` or `winston.format.prettyPrint()` |108| Duplicate logs | Multiple transports to same destination | Review transport configuration |109| Colors not showing | Console transport missing colorize | Add `winston.format.colorize()` to console transport |