How to use Winston logger in Node.js
Winston provides enterprise-grade logging for Node.js applications with multiple transports, custom formatting, and flexible log level management. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented Winston logging in Node.js production services throughout my 11 years of backend development. The most effective approach is configuring Winston with console and file transports for comprehensive logging. This method enables simultaneous logging to multiple destinations with different formats and levels.
Install winston and configure with multiple transports for console and file logging.
const winston = require('winston')
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
),
transports: [
new winston.transports.File({
filename: 'logs/error.log',
level: 'error'
}),
new winston.transports.File({
filename: 'logs/combined.log'
})
]
})
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
}))
}
logger.info('Application started', { port: 3000, env: process.env.NODE_ENV })
logger.error('Database connection failed', { error: new Error('Connection timeout') })
logger.warn('Cache miss', { key: 'user:123' })
logger.debug('Request received', { method: 'GET', path: '/api/users' })
module.exports = logger
Here winston.createLogger creates the logger instance with configurable log level from environment variables. The format.combine adds timestamps, error stack traces, and JSON formatting. File transports write logs to separate files: error.log for errors only and combined.log for all levels. The development-only console transport uses colorized simple format for readable terminal output. Metadata objects provide context for each log entry, making debugging and monitoring more effective.
Best Practice Note:
This is the Winston configuration we use in CoreUI Node.js production services for reliable logging with file rotation and monitoring integration. Add winston-daily-rotate-file for automatic log rotation, integrate with logging services like Datadog or CloudWatch using custom transports, and use child loggers with default metadata for request-scoped logging with correlation IDs.



