DEV Community

Cover image for A Comprehensive Guide to Express Middleware (Morgan)
TANITOLUWA IFEGBESAN
TANITOLUWA IFEGBESAN

Posted on • Updated on

A Comprehensive Guide to Express Middleware (Morgan)

Greetings, dear readers! 🌟
(Background music softly playing: "No Role Modelz" by J. Cole)

Today, we are delving into the world of the Morgan middleware. In this article, we'll primarily focus on integrating Morgan with Express. But fret not, we'll provide examples involving other use cases as well.

What is Morgan?
Morgan is an npm module and middleware designed for logging HTTP request information to your console. It's an invaluable tool for developers seeking deeper insights into the data flowing through their applications.

Installation
Installing Morgan is a breeze, much like most npm libraries. Simply run:

npm install morgan

That's it! No stress, no fuss.

Now, let's dive into the nitty-gritty.

Creating Custom Morgan Functions

To create custom Morgan functions, we'll follow the format and options specified in the documentation. According to the official documentation, "The format argument may be a string of a predefined name, a format string, or a function that produces a log entry."
This function receives three arguments: tokens, req, and res. tokens is an object containing all defined tokens, req represents the HTTP request, and res is the HTTP response.
The function should return a string to be logged, or undefined/null to skip logging.

Here are some of the options you can utilize:

  • immediate: This option writes log lines on request, rather than on response. Even if the server crashes, requests will still be logged, but response data, such as response codes and content length, will not be available for logging.

  • skip: You can specify a function to determine whether logging should be skipped. The default behavior is to log all requests. For example, you can configure Morgan to only log error responses:


morgan('combined', {
  skip: function (req, res) { return res.statusCode < 400; }
})

Enter fullscreen mode Exit fullscreen mode
  • stream: This option allows you to define the output stream for writing log lines. By default, it writes to process.stdout.

Predefined Formats and Tokens

Morgan offers predefined formats and tokens to simplify your logging process. These formats include:

  • Combined: Standard Apache combined log output.
  • Common: Standard Apache common log output.
  • Dev: Concise output with color coding for different response status codes, ideal for development use.
  • Short: A shorter version of the default format, including response time.
  • Tiny: A minimal output format.

Examples

Now, let's put it all into action. In this Express example, we integrate Morgan with the 'combined' format:

var express = require('express')
var morgan = require('morgan')

var app = express()

app.use(morgan('combined'))

app.get('/', function (req, res) {
  res.send('Hello, world!')
})

Enter fullscreen mode Exit fullscreen mode

Available Tokens

Morgan provides several tokens for logging data. Here are some of the key tokens you can use:

  • :date[format]: Displays the current date and time in different formats.
  • :http-version: Shows the HTTP version of the request.
  • :method: Represents the HTTP method used in the request.
  • :referrer: Displays the Referrer header of the request.
  • :remote-addr: Reveals the remote address of the request.
  • :remote-user: Indicates the user authenticated through Basic auth.
  • :req[header]: Logs the specified header of the request.
  • :res[header]: Logs the specified header of the response.
  • :response-time[digits]: Logs the time taken from request reception to response header writing.
  • :status: Logs the status code of the response.
  • :total-time[digits]: Logs the time from request reception to the response's completion.
  • :url: Displays the URL of the request.
  • :user-agent: Logs the User-Agent header contents of the request.

You can even create custom tokens using the morgan.token() method. Just provide a name and a callback function. Be cautious, as creating a new token with a predefined token's name will overwrite it.

Creating Custom Tokens Example

Suppose we want to create a custom token called 'type' that logs the 'Content-Type' header of the request:

morgan.token('type', function (req, res) { return req.headers['content-type']; })

And that's the lowdown on Morgan! Whether you're a seasoned developer or just starting out, this middleware can help you gain valuable insights into your HTTP requests. So, go ahead, integrate it into your Express projects, and start logging like a pro! πŸ’»πŸš€πŸ“

For more info check out the official documentation - https://github.com/expressjs/morgan

The examples used here were from the documentation.

Thank you for tuning in! Stay tuned for more tech tips and insights.
(Background music softly playing: "Merci Beaucoup" by Pop Smoke)

Top comments (0)