Implementing a logger in Node application

Why is logging important in any backend application?

Logging is one of the key aspect for developing any backend application. If we are working on any backend application, then debugging the application and finding exact bug in the code for certain problem can be a gruesome job. This is place where we could assign this task to a logger, which logs every activity at the backend and gives the developer or a team the snapshot of those activities. So, I’ll be discussing some best practices which I learnt this week about logging in nodejs.

Using Winston logger for node application

I’ll be trying to the discuss about one of the most successful logger for any javascript application i.e. winston logger.

Setting up the winston Logger

Before actually talking about setting it(winston) up in the application, I’ll be sharing my project structure below which explains how the project is structured in MVC format.

Project Structure
Project Structure

As we can see the entry point for our application is app.js and our main route-controllers are placed in controllers directory. Now, let us create a new class and directory for our logger in order to keep our workspace clean and modular.

$ npm install winston --save
const winston = require('winston);

Complete code

// winston-logger.js
const winston = require("winston");

class Logger {
  constructor(applicationName) {
    this.applicationName = applicationName || "defaultAppName";

    this.logFormat = winston.format.printf((info) => {
      const formattedDate = info.timestamp.replace("T", " ").replace("Z", "");
      return `[${formattedDate}][${this.applicationName}][${info.level}]${info.message};`;
    });

    this.winston = winston.createLogger({
      level: global.logLevel || "info",
      // level: "debug",
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.colorize(),
        this.logFormat
      ),
      transports: [new winston.transports.Console({})],
    });
  }
}
const logger = new Logger();
module.exports = logger;
// Usage in some other file(Please don't include below lines in winston-logger.js file itself)
logger.winston.info('Server started...');
logger.winston.error('Some error occurred...');