loading...

How to Log Node.js Application Properly

ganeshmani profile image GaneshMani Originally published at cloudnweb.dev ・7 min read

In this article, we will see how to log node.js application properly.

Before we get into the article, we will see why we need to log an application. Let's say that we are building a simple Node.js application and application crashes at some point. it will be easy to debug an application if we are in the development phase.

. before we get into the article, we will see why we need to log an application. Let's say that we are building a simple Node.js application and application crashes at some point. it will be easy to debug an application if we are in the development phase.

But, what happens if the application is already in production and we have much less time to solve the bug in production.

To solve these problems, Logging becomes a crucial part of software development. we will see how to log a Node.js application using Winston

Content Summary

  • Getting Started with winston
  • Different Log Levels in winston
  • Formats in Log Entries
  • Log to a file and console

Getting Started with Winston

winston is a universal Logging library in Node.js ecosystem. you can ask why can't we just use console.log(). problem with console log is you cannot turn it off or add log levels to it. For logging, we usually have requirements, which the console module can't do.

let's create a simple application with Winston Logging.

npm init --yes
npm install --save express body-parser cors winston 
  • express - Express is Node.js Framework to handle the Request and Response
  • body-parser - body-parser is to handle the Form POST Request Body
  • cors - cors is used to handle the Cross-Origin Request like if your front end app and backend are in different ports.
  • winston - Winston is logging library which we are going to use log our application

create a file called app.js and add the following code

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : false}));

app.get('/',(req,res) => {
    res.send("Hello From Cloudnweb");
})

app.listen(3000,() => {
    console.log(`app is listening to port 3000`);
})

Now, you need to add a file called logger.js and add the following code

const { createLogger,format,transports } = require('winston');

const logger = createLogger({
    level : 'debug',
    format : format.combine(format.simple()),
    transports : [
        new transports.Console()
    ]
});

module.exports = logger;
  • createLogger - createLogger is a function which combines the different configuration parameters
  • level - level is nothing but different log level. we will come to this part later of this article
  • format - the format is the way we display the log message. there are different formats. we will see one by one
  • transports - transports sets where you want to log the information. we can log it in the console or a file

After that, you need add the logger.js in app.js.

const express = require('express');
const bodyParser = require('body-parser');
const logger = require('./logger');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : false}));

app.get('/',(req,res) => {
    logger.info("Logger works");
    res.send("Hello From Cloudnweb");
})

app.listen(3000,() => {
    console.log(`app is listening to port 3000`);
})

Logger

you will something like this as an output. yayy!!.

Log Levels in Winston

there are different log levels in Winston which are associated with different integer values

{ error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 }

we can define the level that we want to see the log.. For Example, if we define the Logger level as debug . we cannot see the log of silly in the application. we need to modify it as silly in our application

const logger = createLogger({
    level : 'silly',
    format : format.combine(format.simple()),
    transports : [
        new transports.Console()
    ]
});
logger.info("info level");
logger.debug("debug level");
logger.silly("silly info");

Formats in Log

we can use different formats that we want to see the log messages. For Example, we can colorize the log messages.

const { createLogger,format,transports } = require('winston');


const logger = createLogger({
    level : 'debug',
    format : format.combine(format.colorize(),format.simple()),
    transports : [
        new transports.Console()
    ]
});

module.exports = logger;

we can also combine several different formats for the log messages. one important feature is adding Timestamps to the message log

const { createLogger,format,transports } = require('winston');


const logger = createLogger({
    level : 'debug',
    format: format.combine(
        format.colorize(),
        format.timestamp({
          format: 'YYYY-MM-DD HH:mm:ss'
        }),
        format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
      ),
    transports : [
        new transports.Console()
    ]
});

module.exports = logger;

the log message will be something like this,

Log to a File

it's kind of tough to find the log of a particular bug in an application. to solve this problem, we can write the logs to a file and refer it whenever we want. modify the logger.js as follows

'use strict';
const { createLogger, format, transports } = require('winston');
const fs = require('fs');
const path = require('path');

const env = process.env.NODE_ENV || 'development';
const logDir = 'log';

// Create the log directory if it does not exist
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir);
}

const filename = path.join(logDir, 'app.log');

const logger = createLogger({
  // change level if in dev environment versus production
  level: env === 'development' ? 'debug' : 'info',
  format: format.combine(
    format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss'
    }),
    format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
  ),
  transports: [
    new transports.Console({
      level: 'info',
      format: format.combine(
        format.colorize(),
        format.printf(
          info => `${info.timestamp} ${info.level}: ${info.message}`
        )
      )
    }),
    new transports.File({ filename })
  ]
});

module.exports = logger;

Firstly, it checks whether a folder called log already exists. if it is not present, it will create the folder and create a filename called app.log

transports - it is the place where we define the file log and console log. it configures the log locations.

once you added the file log, you can run the code with node app.js . you will see the log directory and log info will be stored in the app.log

you did it.. this is the way we can log our application and debug it without interrupting the production server

References :

https://blog.risingstack.com/node-js-logging-tutorial/

https://www.digitalocean.com/community/tutorials/how-to-use-winston-to-log-node-js-applications

Posted on by:

ganeshmani profile

GaneshMani

@ganeshmani

Full Stack Engineer. Currently focusing on Javascript, React, GraphQL, and Nodejs.

Discussion

markdown guide