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
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 --yes2npm install --save express body-parser cors winston
create a file called app.js and add the following code
1const express = require("express")2const bodyParser = require("body-parser")3const app = express()45app.use(bodyParser.json())6app.use(bodyParser.urlencoded({ extended: false }))78app.get("/", (req, res) => {9 res.send("Hello From Cloudnweb")10})1112app.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")23const logger = createLogger({4 level: "debug",5 format: format.combine(format.simple()),6 transports: [new transports.Console()],7})89module.exports = logger
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()56app.use(bodyParser.json())7app.use(bodyParser.urlencoded({ extended: false }))89app.get("/", (req, res) => {10 logger.info("Logger works")11 res.send("Hello From Cloudnweb")12})1314app.listen(3000, () => {15 console.log(`app is listening to port 3000`)16})
Logger
you will something like this as an output. yayy!!.
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")
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")23const logger = createLogger({4 level: "debug",5 format: format.combine(format.colorize(), format.simple()),6 transports: [new transports.Console()],7})89module.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")23const 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})1415module.exports = logger
the log message will be something like this,
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")56const env = process.env.NODE_ENV || "development"7const logDir = "log"89// Create the log directory if it does not exist10if (!fs.existsSync(logDir)) {11 fs.mkdirSync(logDir)12}1314const filename = path.join(logDir, "app.log")1516const logger = createLogger({17 // change level if in dev environment versus production18 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})3839module.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
No spam, ever. Unsubscribe anytime.