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
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
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;
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!!.
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”);
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,
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