我正在使用 NLog 进行日志记录。我需要记录打开网站的用户的 IP 地址。
为此,我正在使用 aspnet-request-ip
NLog 的属性。文档在这里:https://github.com/NLog/NLog/wiki/AspNet-Request-IP-Layout-Renderer
我在 NLog 配置中的布局现在如下所示:
layout='"${longdate:universalTime=true}","${level}",${aspnet-request-ip},"${message}"'
问题是 - 记录的 IP 地址是托管网站的机器的 IP。但我需要打开/请求网站的用户的 IP。我需要登录请求/打开网站的 IP。
我怎样才能做到这一点?或者为什么
aspnet-request-ip
正在记录主机 IP 地址,而不是用户/客户端 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.
注意:不要为无负载平衡的情况启用 CheckForwardedForHeader,因为用户可以通过发送该 header 来发送 IP。
见 docs
关于asp.net - NLog aspnet-request-ip 属性只记录负载均衡器的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58558962/