Winston Logger 101

AtharavRaj Singh Yadav
AtharavRaj Singh Yadav
3 min readMar 10, 2023

--

Winston is a popular and versatile logging library in the Node.js ecosystem. It provides a simple and consistent API for logging messages from your application, and its modular design allows for easy customization and extensibility.

Photo by Fotis Fotopoulos on Unsplash

Installing Winston

To use Winston in your Node.js application, you can install it via npm:

npm install winston

Once installed, you can require it in your code:

const winston = require('winston');

Logging Levels

Winston supports several logging levels, each corresponding to a different severity level of message. The available levels are, in increasing order of severity:

  • silly
  • debug
  • verbose
  • info
  • warn
  • error

You can set the logging level for your Winston logger by calling the level method:

const logger = winston.createLogger({
level: 'info',
transports: [
new winston.transports.Console(),
],
});

In this example, we’re creating a logger that will only log messages of severity info or higher. We're also configuring it to log to the console via the built-in Console transport.

Logging Messages

Once you have a logger instance, you can use it to log messages by calling the appropriate method for the desired logging level:

logger.info('This is an info message.');
logger.warn('This is a warning message.');
logger.error('This is an error message.');

Each of these methods takes a string argument representing the message to be logged.

Customizing Winston

Winston provides a wide range of customization options, from specifying your own log format to using custom transports to send logs to external services. For example, to log messages to a file instead of the console, you can use the File transport:

const logger = winston.createLogger({
level: 'info',
transports: [
new winston.transports.File({ filename: 'app.log' }),
],
});

This will create a logger that logs to the file app.log in the current working directory.

Using Winston with Express

Winston can be easily integrated with Express, a popular Node.js framework for building web applications. You can create a middleware function that logs incoming requests and outgoing responses:

const express = require('express');
const winston = require('winston');
const app = express();const logger = winston.createLogger({
level: 'info',
transports: [
new winston.transports.Console(),
],
});
app.use((req, res, next) => {
logger.info(`${req.method} ${req.url}`);
res.on('finish', () => {
logger.info(`${res.statusCode} ${res.statusMessage}; ${res.get('Content-Length') || 0}b sent`);
});
next();
});
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});

In this example, we’re creating an Express application and a Winston logger. We’re then creating a middleware function that logs incoming requests using the info level, and outgoing responses using the finish event of the response object. Finally, we're defining a route that sends a simple "Hello, world!" message, and starting the server on port 3000.

Best Practices

Here are some best practices when using Winston in your Node.js application:

  • Use different loggers for different parts of your application, so you can easily filter and analyze your logs.
  • Use appropriate logging levels for each message. For example, use info for general information messages, warn for non-fatal warnings, and error for critical errors that require immediate attention.
  • Use structured logging, where each log message includes relevant metadata such as the timestamp, the logger name, and the severity level. This makes it easier to search and analyze your logs.
  • Be careful when logging sensitive data such as passwords or credit card numbers. Make sure to properly sanitize and obfuscate such data before logging it.

Conclusion

Winston is a powerful and flexible logging library that can help you keep track of what’s happening in your Node.js application. Whether you need to log to the console, a file, or an external service, Winston has you covered. With its simple API and rich customization options, it’s a great choice for any Node.js project. By following best practices and using Winston effectively, you can gain valuable insights into your application’s behavior and improve its overall quality.

--

--