expressjs / morgan

HTTP request logger middleware for node.js
MIT License
7.95k stars 536 forks source link

req.route.path value is undefined #270

Open brijeshshah13 opened 1 year ago

brijeshshah13 commented 1 year ago

Description

I'm using morgan logger version 1.9.1 in a service and I'm using custom format function as mentioned in their instructions. In the custom format function, I'm accessing req.route.path as shown in the code below:

app.use(logger(function (tokens, req, res) {
    try {
        const responseTimeInMS = tokens['response-time'](req, res);
        const statusCode = tokens['status'](req, res);
        const path = req.route.path;
    } catch (err) {
        console.log(err)
    }
}));

The issue is that out of all the requests that I receive on the server, for some of them I get req.route as undefined due to which I don't get the value of path. Likewise, for some requests, probably the same ones, I get values of variables responseTimeInMS & statusCode as undefined. I'm not sure what the issue can be here. Any help is appreciated.

brijeshshah13 commented 1 year ago

@ryhinchey @dougwilson Kindly check

joewagner commented 1 year ago

@brijeshshah13 I believe the request object is passed down from earlier middleware. The existence of req.route.path is dependent on what kind of server and ealier middleware you are running. There's no way to tell from your code snippet, but I would guess that you are putting the logger middleware before the middleware that adds the req.route.path you are expecting. If you run your application with the inspector enabled it might enable you to find the problem

sarfaraz-mohammad commented 1 year ago

@brijeshshah13 are you able to resolve issue? if not can you share you server.js file where you calling logger middleware