expressjs / morgan

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

Custom logging with IP #215

Closed loretoparisi closed 4 years ago

loretoparisi commented 4 years ago

I have wrote a tiny middleware to get client's IP:

// adapted from https://stackoverflow.com/questions/10849687/express-js-how-to-get-remote-client-address
var getIpInfoMiddleware = function (req, res, next) {
                var client_ip;
                if (req.headers['cf-connecting-ip'] && req.headers['cf-connecting-ip'].split(', ').length) {
                    var first = req.headers['cf-connecting-ip'].split(', ');
                    client_ip = first[0];
                } else {
                    client_ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
                }
                req.ip = client_ip;
                next();
            };
            self.app.use(getIpInfoMiddleware);

Now to print req.ip to every morgan combined logging?

dougwilson commented 4 years ago

By default this library will use the req.ip value https://github.com/expressjs/morgan/blob/master/README.md#remote-addr

loretoparisi commented 4 years ago

@dougwilson ok thank you, I'm not sure that it will consider req.headers['x-forwarded-for'], req.headers['x-real-ip'], etc.

dougwilson commented 4 years ago

Mogran will only consider what is there in the documentation link 👍