How to Log Node.js Application Properly
Tags: showdev, node
Published: 2019-05-18 14:36:58

---
title: How to Log Node.js Application Properly
published: true
description: How to Log node.js application using winston
tags: showdev,node
canonical_url : https://cloudnweb.dev/2019/05/how-to-log-node-js-application-properly/
---
<!-- wp:paragraph -->
<p>In this article, we will see how to log node.js application properly. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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 <a href="https://cloudnweb.dev/category/web-dev/">Node.js</a> application and application crashes at some point. it will be easy to debug an application if we are in the development phase.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>. 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 <a href="https://cloudnweb.dev/category/web-dev/">Node.js</a> application and application crashes at some point. it will be easy to debug an application if we are in the development phase.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>But, what happens if the application is already in production and we have much less time to solve the bug in production. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To solve these problems, Logging becomes a crucial part of software development. we will see how to log a Node.js application using Winston</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Content Summary</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Getting Started with winston</li><li>Different Log Levels in winston</li><li>Formats in Log Entries</li><li>Log to a file and console</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Getting Started with Winston</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>winston is a universal Logging library in Node.js ecosystem. you can ask why can't we just use <strong>console.log().</strong> problem with console log is you cannot turn it off or add log levels to it. For logging, we usually have requirements, which the&nbsp;<code>console</code>&nbsp;module can't do. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>let's create a simple application with Winston Logging.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>npm init --yes
npm install --save express body-parser cors winston </code></pre>
<!-- /wp:code -->

<!-- wp:list -->
<ul><li><strong>express</strong> - Express is Node.js Framework to handle the Request and Response</li><li><strong>body-parser</strong> - body-parser is to handle the Form POST Request Body</li><li><strong>cors</strong> - cors is used to handle the Cross-Origin Request like if your front end app and backend are in different ports.</li><li><strong>winston</strong> -  Winston is logging library which we are going to use log our application</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>create a file called <strong>app.js </strong>and add the following code</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><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`);
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Now, you need to add a file called <strong>logger.js</strong> and add the following code</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const { createLogger,format,transports } = require('winston');

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

module.exports = logger;</code></pre>
<!-- /wp:code -->

<!-- wp:list -->
<ul><li><strong>createLogger</strong> - createLogger is a function which combines the different configuration parameters</li><li><strong>level</strong> - level is nothing but different log level. we will come to this part later of this article</li><li><strong>format</strong> - the format is the way we display the log message. there are different formats. we will see one by one</li><li><strong>transports</strong> - transports sets where you want to log the information. we can log it in the console or a file</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>After that, you need add the<strong> logger.js</strong> in <strong>app.js</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>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`);
})</code></pre>
<!-- /wp:code -->

<!-- wp:image {"id":464} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/05/winston_log-1024x108.png" alt="" class="wp-image-464"/><figcaption>Logger</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>you will something like this as an output. yayy!!. </p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":466,"align":"center","width":586,"height":332} -->
<div class="wp-block-image"><figure class="aligncenter is-resized"><img src="https://cloudnweb.dev/wp-content/uploads/2019/05/i_did_it.gif" alt="" class="wp-image-466" width="586" height="332"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Log Levels in Winston</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>there are different log levels in Winston which are associated with different integer values</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>{ error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 }</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>we can define the level that we want to see the log.. For Example, if we define the Logger level as <strong>debug</strong> .  we cannot see the log of <strong>silly </strong>in the application.  we need to modify it as silly in our application</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const logger = createLogger({
    level : 'silly',
    format : format.combine(format.simple()),
    transports : [
        new transports.Console()
    ]
});</code></pre>
<!-- /wp:code -->

<!-- wp:code -->
<pre class="wp-block-code"><code>logger.info("info level");
logger.debug("debug level");
logger.silly("silly info");</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3>Formats in Log</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>we can use different formats that we want to see the log messages. For Example, we can colorize the log messages.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>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;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>we can also combine several different formats for the log messages. one important feature is adding <strong>Timestamps</strong> to the message log</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>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;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>the log message will be something like this,</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":468} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/05/winston.png" alt="" class="wp-image-468"/></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Log to a File </h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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<strong> logger.js</strong> as follows</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>'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;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Firstly, it checks whether a folder called <strong>log</strong> already exists. if it is not present, it will create the folder and create a filename called <strong>app.log</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>transports </strong>- it is the place where we define the file log and console log. it configures the log locations.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>once you added the file log, you can run the code with <strong>node app.js</strong> . you will see the <strong>log </strong>directory and log info will be stored in the <strong>app.log</strong></p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":470} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/05/log-1024x691.png" alt="" class="wp-image-470"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>you did it.. this is the way we can log our application and debug it without interrupting the production server</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":472,"align":"center","width":579,"height":326} -->
<div class="wp-block-image"><figure class="aligncenter is-resized"><img src="https://cloudnweb.dev/wp-content/uploads/2019/05/claps-1.gif" alt="" class="wp-image-472" width="579" height="326"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>References : </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://blog.risingstack.com/node-js-logging-tutorial/">https://blog.risingstack.com/node-js-logging-tutorial/</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://www.digitalocean.com/community/tutorials/how-to-use-winston-to-log-node-js-applications">https://www.digitalocean.com/community/tutorials/how-to-use-winston-to-log-node-js-applications</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->