Introduction to Winston
Winston is a versatile and popular logging library for Node.js applications. It allows developers to log information to various transports including console, files, databases, and more. Logging is an essential part of monitoring and debugging applications, and Winston provides a powerful API to help you achieve this efficiently.
Installation
npm install winston
Basic Usage
To start using Winston, you need to create a logger instance:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'app.log' })
]
});
logger.info('Hello, Winston!');
logger.error('Something went wrong!');
Multiple Transports
You can log to multiple transports simultaneously:
const logger = winston.createLogger({
level: 'info',
format: winston.format.simple(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' }),
new winston.transports.File({ filename: 'error.log', level: 'error' })
]
});
logger.info('Logging to multiple transports');
logger.error('Error example');
Log Formatting
Winston supports customizable log formats:
const { combine, timestamp, printf } = winston.format;
const myFormat = printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
});
const logger = winston.createLogger({
format: combine(
timestamp(),
myFormat
),
transports: [new winston.transports.Console()]
});
logger.info('Custom format example');
Querying Logs
You can query logs programmatically:
const options = {
from: new Date() - 24 * 60 * 60 * 1000,
until: new Date(),
limit: 10,
start: 0,
order: 'desc',
fields: ['message']
};
logger.query(options, (err, results) => {
if (err) {
console.error('Error querying logs', err);
}
console.log('Log Query Results:', results);
});
Exception Handling
Handle uncaught exceptions using Winston:
const logger = winston.createLogger({
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'exceptions.log' })
],
exceptionHandlers: [
new winston.transports.File({ filename: 'exceptions.log' })
]
});
throw new Error('Uncaught Exception Example');
Application Example
Here is a simple application that demonstrates Winston logging:
const express = require('express');
const winston = require('winston');
const app = express();
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'app.log' })
]
});
app.get('/', (req, res) => {
logger.info('Home page accessed');
res.send('Home Page');
});
app.get('/error', (req, res) => {
logger.error('An error occurred');
res.status(500).send('Error Page');
});
app.listen(3000, () => {
logger.info('Server is running on port 3000');
});
With this setup, you can track access to your routes and any errors that occur.
Hash: ea66f06bd8d37bbf7f74fcf064cd23af4aa104eadb0aa13684484b88a7e1c202