NLog aspnet-request-ip 属性 只记录负载均衡器IP地址

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

我正在使用 NLog 进行日志记录。我需要记录打开网站的用户的 IP 地址。

为此,我使用了 NLog 的 aspnet-request-ip 属性。文档在这里:https://github.com/NLog/NLog/wiki/AspNet-Request-IP-Layout-Renderer

我在 NLog 配置中的布局现在如下所示:

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

问题是 - 记录的 IP 地址是托管网站的机器的 IP。但是我需要 opening/requesting 网站用户的 IP。我需要登录网站的IP是requested/opened.

我该怎么做?或者为什么 aspnet-request-ip 正在记录主机 IP 地址,而不是 user/client IP 地址?

如果您使用的是负载均衡器(在这种情况下),请求 IP 将是负载均衡器的 IP。本质上,您收到的是负载均衡器的请求,所以这是发送方的 IP。

所以你需要:

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

这将获取 X-Forwarded-For header 的 IP,这是负载均衡器发送客户端 IP 的实际标准。参见 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.

注意:不要为 no-load-balanced 情况启用 CheckForwardedForHeader,因为用户可以通过发送 header.

来发送 IP

docs