gpt4 book ai didi

java - 如何在tomcat访问日志中记录客户端IP和X-Forwarded-For IP

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:01:59 27 4
gpt4 key购买 nike

如何在 tomcat 访问日志中记录客户端 IP 和 X-Forwarded-For IP。

我正在使用 %{X-Forwarded-For}i,如果我通过负载均衡器访问,它会记录实际的客户端地址。但是,如果我直接访问 tomcat 实例,则不会记录实际的客户端地址。有没有办法在这两种情况下显示实际的客户端 IP 地址?

最佳答案

来自 http://www.techstacks.com/howto/configure-access-logging-in-tomcat.html :

If you are running a version of tomcat greater than version 6.0.21 or tomcat 7, you can take advantage of the new Remote IP Valve. For access logging, the nice thing about this valve is that it will swap the client IP with an IP address passed with the X-Forwarded-For header—automatically—if an IP address is passed in the X-Forwarded-For header. Loading it is pretty easy. Just add the org.apache.catalina.valves.RemoteIpValve to your server.xml before your AccessLogValve declaration. For example:

 <Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">

<!-- Remote IP Valve -->
<Valve className="org.apache.catalina.valves.RemoteIpValve" />

<!-- Access log processes all example.
Documentation at: /docs/config/valve.html -->

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt"
pattern="combined" resolveHosts="false"/>
-->
</Host>

If you are using a version of tomcat 6 older than 6.0.21 and you want to store the X-Forwarded-For IP address instead, then you could modify the pattern property of your AccessLogValve. You'll need to remove the "common" or "combined" pattern and replace it with one of the following patterns:

Common Log Format: %{X-Forwarded-For}i %l %u %t "%r" %s %b
Combined Log Format: %{X-Forwarded-For}i %l %u %t %r %s %b %{User-Agent}i %{Referer}i

The main problem here, that RemoteIP Valve does take care of, is that you'll only get the X-Forwarded-For address in the logs. If you hit the app server directly, bypassing the device that is inserting the X-Forwarded-For header in the request, you won't get an IP address logged. You will still log a request—you just will not know where it came from.

关于java - 如何在tomcat访问日志中记录客户端IP和X-Forwarded-For IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48103673/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com