Winston Logger
Winston is a versatile logging library for JavaScript and Node.js, designed to support multiple transports for logs. It allows flexible configuration of log formatting and levels, decoupling the logging process from storage implementation. The current stable version is 3.19.0, with regular patch and minor releases addressing fixes and new features.
Common errors
-
TypeError: winston.Logger is not a constructor
cause Attempting to instantiate `winston.Logger` directly, which was common in Winston v2 but is no longer the correct pattern in v3.fixUse `winston.createLogger()` to create a logger instance instead of `new winston.Logger()`. -
TS2345: Argument of type 'LogCallback' is not assignable to parameter of type '...' (e.g., 'LogEntry')
cause Your TypeScript code is attempting to use the `LogCallback` type or pass a `LogCallback` where it's no longer expected after v3.15.0.fixRemove `LogCallback` from your type annotations or function signatures; the type was removed as the underlying functionality was unsupported. -
Error: EACCES: permission denied, open 'error.log'
cause The Node.js process does not have write permissions to the directory where Winston is attempting to create or write log files.fixEnsure the user running the Node.js process has appropriate write permissions for the log file directory, or configure Winston to write logs to a different, accessible location.
Warnings
- breaking Winston v3 introduces significant breaking changes compared to v2, including a new API for logger instantiation and transport configuration.
- gotcha Using the default logger (`require('winston')` or `import winston from 'winston'`) without explicitly adding any transports can lead to high memory usage as logs are buffered indefinitely.
- breaking The `LogCallback` type was removed from Winston's TypeScript definitions in v3.15.0 because the underlying library did not actually support this functionality.
Install
-
npm install winston -
yarn add winston -
pnpm add winston
Imports
- winston
import winston from 'winston'
Quickstart
import winston from 'winston';
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
// Log all errors to error.log
new winston.transports.File({ filename: 'error.log', level: 'error' }),
// Log all info and higher to combined.log
new winston.transports.File({ filename: 'combined.log' })
]
});
// Add a console transport if not in production
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
// Example logging
logger.info('User logged in', { userId: 123 });
logger.warn('Deprecated feature used');
logger.error('Failed to connect to database', { error: 'Connection refused' });