Search code examples
asp.netasp.net-mvcnlog

NLog aspnet-request-ip property only logs the load balancer IP address


I am using NLog for logging. I need to log the IP address of the user who is opening the website.

For that purposes, I am using the aspnet-request-ip property of NLog. The documentation is here: https://github.com/NLog/NLog/wiki/AspNet-Request-IP-Layout-Renderer

My layout in NLog config looks like the following right now:

layout='"${longdate:universalTime=true}","${level}",${aspnet-request-ip},"${message}"'

The problem is - that the logged IP address is the IP of the machine which is hosting the website. But I need the IP of the user who is opening/requesting the website. I need to log from which IP the website is requested/opened.

How can I do this? Or why aspnet-request-ip is logging the host IP address, instead of the user/client IP address?


Solution

  • If you're using a load balancer (so in this case), the request IP will be the IP of the load balancer. Essentially you are getting the request of the load balancer, so that's the IP of the sender.

    So you need:

    ${aspnet-request-ip:CheckForwardedForHeader=true}
    

    This will get the IP of the X-Forwarded-For header, which is the de facto standard for sending client IPs by a load balancer. See X-Forwarded-For on MDN

    The X-Forwarded-For (XFF) header is a de-facto standard header for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or a load balancer. When traffic is intercepted between clients and servers, server access logs contain the IP address of the proxy or load balancer only. To see the original IP address of the client, the X-Forwarded-For request header is used.

    Note: don't enable CheckForwardedForHeader for no-load-balanced cases, as an user could send the the IP by sending that header.

    See docs