Home > Enterprise >  Logging proper user ip behind a reverse proxy in GAE
Logging proper user ip behind a reverse proxy in GAE

Time:11-12

I'm using cloudflare as a reverse proxy in front of AppEngine. Hence, in GCP Logging request log, the IP being logged is Cloudflare's.

Behind cloudflare, the actual user IP is req.headers['x-forwarded-for'].split(',')[0], so I've been trying to work through Google Logging log correlation to get it right (in an express middleware):

const forwardedForHeader = req.headers['x-forwarded-for']
const userIp = forwardedForHeader ? forwardedForHeader.split(',')[0] : req.ip
res.on('finish', () => {
    logger.info(req.originalUrl, {
        httpRequest: {
            status: res.statusCode,
            requestUrl: req.originalUrl,
            requestMethod: req.method,
            remoteIp: userIp,
        },
        remoteIp: userIp, // workaround to get remote IP as metadata - GAE has everything else
    })
})

LOGGING_SPAN_KEY & LOGGING_TRACE_KEY are both set properly.

Unfortunately, I'm still getting 2 log entries (GAE generated 1 in request log; mine generated as above).

Is there any way to get the actual user ip in the request log ?

CodePudding user response:

You can take a look into this article: How does Cloudflare handle HTTP Request headers?

To restore original visitor IP addresses at your origin web server, Cloudflare recommends your logs or applications look at CF-Connecting-IP or True-Client-IP instead of X-Forwarded-For since CF-Connecting-IP and True-Client-IP have a consistent format containing only one IP.

I hope this is useful.

CodePudding user response:

You can take a look in this documetn Setting Up Cloud Logging for Node.js. Here explains the popular Bunyan and Winston logging libraries.

  • Related