How to Log Node.js Application properly

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.

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.

1npm init --yes
2npm 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

1const express = require("express")
2const bodyParser = require("body-parser")
3const app = express()
4
5app.use(bodyParser.json())
6app.use(bodyParser.urlencoded({ extended: false }))
7
8app.get("/", (req, res) => {
9 res.send("Hello From Cloudnweb")
10})
11
12app.listen(3000, () => {
13 console.log(`app is listening to port 3000`)
14})

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

1const { createLogger, format, transports } = require("winston")
2
3const logger = createLogger({
4 level: "debug",
5 format: format.combine(format.simple()),
6 transports: [new transports.Console()],
7})
8
9module.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.

1const express = require("express")
2const bodyParser = require("body-parser")
3const logger = require("./logger")
4const app = express()
5
6app.use(bodyParser.json())
7app.use(bodyParser.urlencoded({ extended: false }))
8
9app.get("/", (req, res) => {
10 logger.info("Logger works")
11 res.send("Hello From Cloudnweb")
12})
13
14app.listen(3000, () => {
15 console.log(`app is listening to port 3000`)
16})

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

1{ 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

1const logger = createLogger({
2 level: "silly",
3 format: format.combine(format.simple()),
4 transports: [new transports.Console()],
5})
1logger.info("info level")
2logger.debug("debug level")
3logger.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.

1const { createLogger, format, transports } = require("winston")
2
3const logger = createLogger({
4 level: "debug",
5 format: format.combine(format.colorize(), format.simple()),
6 transports: [new transports.Console()],
7})
8
9module.exports = logger

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

1const { createLogger, format, transports } = require("winston")
2
3const logger = createLogger({
4 level: "debug",
5 format: format.combine(
6 format.colorize(),
7 format.timestamp({
8 format: "YYYY-MM-DD HH:mm:ss",
9 }),
10 format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
11 ),
12 transports: [new transports.Console()],
13})
14
15module.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

1"use strict"
2const { createLogger, format, transports } = require("winston")
3const fs = require("fs")
4const path = require("path")
5
6const env = process.env.NODE_ENV || "development"
7const logDir = "log"
8
9// Create the log directory if it does not exist
10if (!fs.existsSync(logDir)) {
11 fs.mkdirSync(logDir)
12}
13
14const filename = path.join(logDir, "app.log")
15
16const logger = createLogger({
17 // change level if in dev environment versus production
18 level: env === "development" ? "debug" : "info",
19 format: format.combine(
20 format.timestamp({
21 format: "YYYY-MM-DD HH:mm:ss",
22 }),
23 format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
24 ),
25 transports: [
26 new transports.Console({
27 level: "info",
28 format: format.combine(
29 format.colorize(),
30 format.printf(
31 info => `${info.timestamp} ${info.level}: ${info.message}`
32 )
33 ),
34 }),
35 new transports.File({ filename }),
36 ],
37})
38
39module.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

To Read More

Everything you need to know about d...

Docker volume is a persistent data storage mechanism to store the data in docker...

How to remove docker image - Docker...

This guide will cover everything you need to know about removing docker images f...

How to build an Actionable data ta...

In this article, we will see how to build an Actionable data table using a react...