Log your Node Js error in a log file like a PRO!

Log your Node Js error in a log file like a PRO!

We all have used console.log() at some point in time but these are just for debugging purpose only. It's not recommended in a production-level app.

If you'll use them in your production level app, this may not help you in finding the exact error and when did that occur.

To have a proper track of your errors, we must use something reliable so that we can check for our error later.

One of the best way to identify all of your error is to make a log file for all of your errors.

But hey, how will I create log files for all of my future errors?

I was working on my office project where I learnt that it's quite easy to implement, all thanks to Vibhor sir.

Don't worry. You don't have to create log files for your errors manually.

The best thing about Node js is that it has packages for everything you can think of😉.

Using Winston

Winston makes it super easy in logging your errors. With over 6,155,906 installs each week, you can think how much power it has.

You can easily implement it in your code.

Start by installing Winston

npm i winston

We, need another package to have our logs rotated at a particular interval. Logs can be rotated based on a date, size limit, and old logs can be removed based on the count of elapsed days.

npm i winston-daily-rotate-file

The DailyRotateFile transport can rotate files by minute, hour, day, month, year or weekday.

The next step is to set up the code for Winston.

Let's create a file for Winston. You can name it whatever you want.

I'll be naming logger.js

const winston = require("winston");
require("winston-daily-rotate-file");

const dashLog = new winston.transports.DailyRotateFile({
  filename: "./logs/dash-%DATE%.log",
  datePattern: "YYYY-MM-DD",
  zippedArchive: true,
  maxSize: "20m",
});

const dash = winston.createLogger({
  transports: [
    dashLog,
    new winston.transports.Console({
      colorize: true,
    }),
  ],
});

module.exports = {
  dashLogger: dash,
};

Some of the options which I've used here are filename, datePattern, zippedArchive, maxSize.

filename: This will let you name your log files the way you want.

datePattern: It is used to dictate the frequency of the file rotation.

zippedArchive: A boolean to define whether or not to gzip archived log files. (default: 'false')

maxSize: Maximum size of the file after which it will rotate.

Now, open your starting file of node js. Mine is app.js

To use this logger, we just need to import our logger.js file and instead of using console.log(), we can use our custom logger.

In our app.js

const express = require("express");

const { dashLogger } = require("./logger");

const app = express();

app.use(express.json());

app.get("/", (req, res) => {
  try {
    return res.render("view", {
      data,
    });
  } catch (error) {
    console.error(error);
    dashLogger.error(`Error : ${error},Request : ${req.originalUrl}`);
    res.render("400");
  }
});

app.listen(3000, () => {
  console.log("Server started");
});

What we have done here is that we are wrapping our code in a try-catch block and if it throws an error, our logger will create a log file inside of the logs directory.

Here, I've also kept req.originalUrl so that it would be easy to detect where is the actual point of error. It will log the error with the actual route.

In this way, we can easily have the logs of our application and it will help us in finding the error easily.

Thanks

I hope this post will help you in debugging your code much easier. If you found this code helpful and the logger actually helped you at any point of time, just leave a comment below and let me know.

Thanks for the time, see you in my next post.

Did you find this article valuable?

Support Learn Syntax by becoming a sponsor. Any amount is appreciated!