How to logs all requests in ExpressJS server

MDN's photo

Published on Jun 9, 2021

1 min read

Subscribe to my newsletter and never miss my upcoming articles

The express-generator boilerplate definitely uses morgan as logger. I saw no problems with that package, so I decided to keep it working. Here is the code in NodeJS:

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

        ':method :status :url :param :data - :responseData :res[content-length] - :response-time ms - :remote-addr :user-agent :date[iso]'
morgan.token('param', function (req, res, param) {
    return JSON.stringify(req.query)
morgan.token('responseData', (req, res) => {
    return res.__custombody__
morgan.token('data', (req, res) => {
    return JSON.stringify(req.body)

I want to logs almost everything of requests. These are methods, HTTP code status, URL, param query, payload data, response data and how long servers took to process a single request, etc. I am totally happy with that kind of logs and they often helped me a lot in debugging or tracing errors.

Note that these logs can contain sensitive data of users, such as password sent in payload, JWT token. You should carefully use it in production. Furthermore, you can filter sensitive informations before take log. That can be easily implemented.

Share this