Skip to main content

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.jsapplication 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

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...