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

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...