Raddy Website Design & Development Tutorials

Learn Morgan – HTTP request logger for NodeJs

By Raddy in NodeJs ·

Today we are going to explore the NPM middleware called Morgan. Morgan is a Node.js middleware to log HTTP requests. Monitoring and reading logs can help you better understand how your application behaves.

Tutorial Code

To do that, create a new project folder called “NodeJs Morgan” (or whatever you wish) and then run the following command in Command Line (Mac / Linux) or Powershell (Windows).

npm init

This will initialise a new project for you and it’s going to ask you a few questions about your project. The most important one is to give your package a name and then you can just keep pressing enter until the installation is over.

You can skip all questions by adding the “-y” flag like in the example below:

npm init -y

At this point, you should see a file called package.json in your project folder.

Dependencies Installation

We have to install a few dependencies:

[x] express
[x] morgan

Open the Command Line / Terminal / Powershell and install the dependencies listed above just like so:

npm install express morgan

Your packages.json file should look similar to this:

{
  "name": "nodejs-morgan",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1",
    "morgan": "^1.10.0"
  }
}

Basic usage with custom tokens

const express = require('express')
const morgan = require('morgan')
const app = express()
const port = 5000

app.use(morgan(':method :url :status :res[content-length] - :response-time ms :date[web]'))

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

app.get('/about', function (req, res) {
  res.send('About Page!')
})

app.listen(port, () => console.info(`App listening on port ${port}`))

To run your application open Terminal / Command Line and make sure that you are inside your project folder. You can use the ‘cd’ and ‘ls’ commands to see where you are.

Run app.js

node app.js
nodejs start

If you get “App listening on port 5000” you should be able to visit your website under localhost:5000. Make a few requests and you should see the logs coming in.

Write to file

const express = require('express')
const morgan = require('morgan')
var fs = require('fs') // Include FS
var path = require('path') // Include Path
const app = express()
const port = 5000

const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })

app.use(morgan(':method :url :status :res[content-length] - :response-time ms :date[web]', { stream: accessLogStream }))

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

app.get('/about', function (req, res) {
  res.send('About Page!')
})

app.listen(port, () => console.info(`App listening on port ${port}`))

The flag “a” means: Open file for appending. The file is created if it does not exist.

Create custom Token

const express = require('express')
const morgan = require('morgan')
var fs = require('fs') // Include FS
var path = require('path') // Include Path
const app = express()
const port = 5000

const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })

// Custom token with the name of 'type'. You can call it whatever you like
morgan.token('type', function (req, res) { return req.headers['content-type'] })

// Include the custom token at the end
app.use(morgan(':method :url :status :res[content-length] - :response-time ms :date[web] :type', { stream: accessLogStream }))

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

app.get('/about', function (req, res) {
  res.send('About Page!')
})

app.listen(port, () => console.info(`App listening on port ${port}`))

Example:

nodejs morgan logger

Happy logging 🙂

Download

Thank you for reading this article. Please consider subscribing to my YouTube Channel.

More Resources:

Leave a Reply

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