Home > Back-end >  morgan substitute a "-" if a value is not available
morgan substitute a "-" if a value is not available

Time:10-27

morgan(
    ":remote-addr :method :url :status :res[content-length] :response-time ms"
);

For example, if :res[content-length] is not available, then it will print a "-" in its place. How do I change this dash to something else?

CodePudding user response:

The "-" is hardcoded in the compile function here which runs when the value behind the token is undefined.

The tokens method can be used to provide a custom string when the value behind the token is missing, i.e. undefined. You can use it to overwrite predefined tokens used in your format string passed to morgan. Here is an example overwriting the predefined :res token and replacing the - with <!> if the token value is undefined.

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

const app = express()
const origRes = morgan.res

morgan.token('res', function customGetResponseHeader(req, res, field) {
  const resp = origRes(req, res, field)

  if (resp === undefined) {
    // Custom string here
    return '<!>'
  }
})

app.use(morgan(":remote-addr :method :url :status :res[content-length] :response-time ms"))

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

app.listen(3000, 'localhost', () => {
 console.log('listening')
})
  • Related