morgan log with customise

Morgan Log with Customise

As a developer, logging is an essential part of debugging and monitoring our applications. One of the popular logging libraries in Node.js is Morgan, which makes it easy to log HTTP requests. However, sometimes we may want to customize the format and content of the logs to our specific needs.

One way to customize Morgan logs is by using the format option, which allows us to define a custom log format string. This string can include placeholders that will be replaced with values from the request object.


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

const app = express();

// Define custom log format
const logFormat = ':method :url :status :response-time ms - :res[content-length]';

// Use Morgan middleware with custom log format
app.use(morgan(logFormat));

app.get("/", (req, res) => {
  res.send("Hello World!");
});

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

In this example, we define a custom log format string that includes placeholders for the HTTP method, URL, status code, response time, and response content length. We then pass this format string to the Morgan middleware using the format option.

Another way to customize Morgan logs is by using the stream option, which allows us to redirect the logs to a custom output stream. This can be useful if we want to store the logs in a database or send them to a third-party logging service.


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

const app = express();

// Define custom log stream
const logStream = fs.createWriteStream(__dirname + "/access.log", { flags: "a" });

// Use Morgan middleware with custom log stream
app.use(morgan("combined", { stream: logStream }));

app.get("/", (req, res) => {
  res.send("Hello World!");
});

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

In this example, we create a custom log stream using the fs.createWriteStream() method and pass it to the Morgan middleware using the stream option. This will redirect all the logs to the specified file.

In conclusion, Morgan is a powerful logging library that can be easily customized to fit our specific needs. Whether we want to change the log format or redirect the logs to a custom output stream, Morgan has us covered.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe