expressjs / morgan

HTTP request logger middleware for node.js
MIT License
7.92k stars 533 forks source link

Custom tokens returning function string #253

Closed stoneRdev closed 3 years ago

stoneRdev commented 3 years ago

So, as the title kind of suggests, using custom tokens causes the string representation of the function to be logged, not the result of the function.

Minimal Example: server.js


const path = require('path')
const app = require('express')()
const http = require('http').Server(app)
const rfs = require('rotating-file-stream')
const morgan = require('morgan')
morgan.token("local-addr",function getLocalAddrToken(req,res) {
    return req.connection.localAddress
})
//morgan.format("sal",`:local-addr HTTP :http-version :method :url ttr :response-time ms tts :total-time ms`)
morgan.format("sal",function sal(tokens,req,res) {
    return `
    ${tokens['local-addr']} HTTP${tokens['http-version'](req,res)} ${tokens.method(req,res)} ${tokens.url(req,res)} ttr ${tokens['response-time'](req,res)}ms tts ${tokens['total-time'](req,res)}ms
    ${tokens.date(req,res,"iso")}
    `
})
const logFileStream = rfs.createStream(path.resolve(__dirname,"log/access.log"),{
    interval: '1d,',
    compress: 'gzip'
})
app.use(morgan('sal',{stream: logFileStream,console: true}))
app.get('/',(req,res) => {
    res.send("<html><body></body></html>")
});
http.listen(6969,() => {
    console.log(`server listening on port: 6969`)
})

access.log output:

    function getLocalAddrToken(req,res) {
    return req.connection.localAddress
} HTTP1.1 GET / ttr 12.511ms tts 25.574ms
    2021-03-20T02:22:16.254Z
stoneRdev commented 3 years ago

Ahh, I see the error of my ways, please disregard