javascriptnode.jsexpressmorgan

How to use Morgan logger token's value in another variable or functions?


I'm relatively new to Javascript and NodeJS.
I'm trying to use Morgan with Express.js. I have read the documentation regarding it here. Is there any way to reuse the return value from the predefined tokens?

From the documentation, it is stated that you can use something like this:

let express = require('express');
let logger = require('morgan');

let app = express();

app.use(logger(function (tokens, req, res) {
  return [
    tokens.method(req, res),
    tokens.url(req, res),
    tokens.status(req, res),
    tokens.res(req, res, 'content-length'), '-',
    tokens['response-time'](req, res), 'ms'
  ].join(' ')
}));

Can we use the values of the tokens? for example, the value of response-time in another function?

tokens['response-time'](req, res) //Use the value of this in another function

I wish to be able to save the log of time elapsed from the request received until the response sent back to the client into my database. Is there any solution/suggestion regarding this?


Solution

  • I hope this isn't outdated answer with a right method.

    Your approach is right. You can just call the function inside the middleware,

    Here I create other-function.js

    module.exports = (responseTime) => {
        console.log('Hi there, my response time is '+responseTime+' ms')
    }
    

    and my app.js

    let express = require('express');
    let logger = require('morgan');
    let otherFunction = require('./other-function')
    
    let app = express();
    
    app.use(logger(function (tokens, req, res) {
      otherFunction(tokens['response-time'](req, res))
      return [
        tokens.method(req, res),
        tokens.url(req, res),
        tokens.status(req, res),
        tokens.res(req, res, 'content-length'), '-',
        tokens['response-time'](req, res), 'ms'
      ].join(' ')
    }));
    

    So the output will looks like this

    Hi there, my response time is 4.566 ms
    GET / 404 139 - 4.566 ms
    

    Hope this helps.