Categories
JavaScript Answers

How to use Morgan logger with Node.js?

Spread the love

To use Morgan logger with Node.js, we use it as a middleware.

For instance, we write

const express = require("express");
const app = express();
const morgan = require("morgan");

if (app.get("env") === "production") {
  app.use(
    morgan("common", {
      skip: (req, res) => {
        return res.statusCode < 400;
      },
      stream: __dirname + "/../morgan.log",
    })
  );
} else {
  app.use(morgan("dev"));
}

to call morgan with the logger options to create a middleware function for logging.

We set stream to the path of the log file to write to.

And we set skip to a function that returns the condition of the items to skip in the log.

Then we call app.use to use the middleware in our Express app.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *