How to Log Node.js Application properly

How to Log Node.js Application properly

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

Originally published by ganeshmani009 at  cloudnweb.dev

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

Originally published by ganeshmani009 at  cloudnweb.dev

=============================

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Learn More

☞ NestJS Zero to Hero - Modern TypeScript Back-end Development

☞ The Complete Node.js Developer Course (3rd Edition)

☞ Complete Next.js with React & Node - Beautiful Portfolio App

☞ Angular & NodeJS - The MEAN Stack Guide

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ Docker for Node.js Projects From a Docker Captain

☞ Intro To MySQL With Node.js - Learn To Use MySQL with Node!

☞ Node.js Absolute Beginners Guide - Learn Node From Scratch

node-js javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.