如何在Spring-boot应用程序中为Apache Tomcat中的AccessLogValve设置属性requestAttributesEnabled?

时间:2016-10-20 09:44:33

标签: java spring tomcat spring-boot

我们有一个独立的spring-boot应用程序,我们想要设置访问日志模式

    请求中存在
  • X-forwarded-for 标头:它应作为第一个字段包含在日志中
  • X-forwarded-for 标头请求中不存在:应该用远程IP地址替换

当我们使用以下设置运行我们的应用程序时,我们只获取远程IP地址

server.tomcat.accesslog.directory=<path_to_log_director>
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b
server.tomcat.accesslog.prefix=access_log
server.tomcat.accesslog.suffix=.log

例如:

192.168.25.265 - - - [12/Sep/2016:10:20:56 +0200] "GET /myapp HTTP/1.1" 200 125922

我们还尝试将属性server.tomcat.accesslog.pattern设置为

%h %{X-Forwarded-For}i %l %u %t "%r" %s %b

然后我们得到远程IP地址和X-forwarded-for标头值。

例如:

192.168.25.265 192.168.21.65 - - - [12/Sep/2016:10:20:56 +0200] "GET /myapp HTTP/1.1" 200 125922

但是,基于链接https://tomcat.apache.org/tomcat-7.0-doc/config/valve.html,当x-forwarded-for不存在时,tomcat支持此要求包括远程IP地址。这可以通过添加属性'requestAttributesEnabled'

来实现

我们尝试添加该属性     server.tomcat.accesslog.requestAttributesEnabled 但没有发生任何影响。

它似乎没有实现,因为它不在此处:http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

我们使用EmbeddedServletContainerCustomizer的实现实现了一种变通方法,如How do I configure the location and name of tomcat access log in spring-boot?中所述, 我们在哪里添加:

accessLogValve.setRequestAttributesEnabled(true);

它按预期工作。

但是我们希望能够通过spring-boot将requestAttributesEnabled设置为配置属性,例如:

server.tomcat.accesslog.requestAttributesEnabled=true

而不是需要在我们的所有服务中使用此自定义程序。

这个问题是否有更好的解决方案,是否有其他属性可以使用,或者它是否可以在不久的将来交付?

1 个答案:

答案 0 :(得分:3)

你是对的,这个属性没有直接暴露,你所做的是推荐的方法。话虽如此,我已经创建#7367来讨论我们是否应该将其添加为内置属性。请关注该问题以获得进一步的更新。谢谢!