如何使用spring boot配置logback-access.xml

w7t8yxp5  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(504)

我的申请是:

server:
  tomcat:
    accesslog:
      enabled: true
    basedir: my-tomcat

我们使用spring boot 1.4.3.release,我想用以下内容配置logback-access.xml(在src/main/resources下):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- always a good activate OnConsoleStatusListener -->
  <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%h %l %u %user %date "%r" %s %b</pattern>
    </encoder>
  </appender>

  <appender-ref ref="STDOUT" />
</configuration>

我可以在我的tomcat文件夹下看到一个access_log.2017-01-03.log文件,其中包含正确的访问日志,但注意到在我的concole上,似乎没有读取配置文件logback-access.xml。
你知道吗?
埃里克

yi0zb3m4

yi0zb3m41#

是我弄错了,还是SpringBoot不支持这个功能?
资料来源:https://github.com/spring-projects/spring-boot/issues/2609:
嘿,我想让logback访问+tomcat和spring boot一起工作。有人能把它从盒子里拿出来吗?或者有必要设置管道吗?
...

As a workaround, you can copy the access xml from the class path to the filesystem and run it there as part of your configuration class

Files.copy(this.getClass().getResourceAsStream("/logback-access.xml"),Paths.get("log-access.xml"),StandardCopyOption.REPLACE_EXISTING);
logbackValve.setFilename("log-access.xml");

解决方案

使用spring boot ext logback访问:
只需添加依赖项即可:

<dependency>
    <groupId>net.rakugakibox.spring.boot</groupId>
    <artifactId>logback-access-spring-boot-starter</artifactId>
    <version>2.7.0</version>
</dependency>

编辑-logback 1.1.6的其他解决方案+

关于上面提到的Spring Boot问题,有人发了这样的帖子:
由于logback 1.1.6,因此不需要任何解决方法来将logback访问配置文件作为资源加载。参考文献:http://jira.qos.ch/browse/logback-1069
你所要做的就是: logbackValve.setFilename("log-access.xml");

4c8rllxm

4c8rllxm2#

虽然我来晚了,但我还是给后人发了一个简单的工作代码。
这个 logback 的访问日志可以通过以下步骤打印到控制台日志中:
添加 logback-access 附属国

implementation group: 'ch.qos.logback', name: 'logback-access', version: '1.2.3'

注入 TomcatServletWebServerFactory 增加示例值 LogbackValve .

@Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addContextValves(new LogbackValve());
        return tomcat;
    }

添加以下内容 logback-access.xml 进入类路径 resources\conf 目录。

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <Pattern>combined</Pattern>
      <Pattern>[ACCESS] %h %l %u %t{yyyy-MM-dd HH:mm:ss.SSS} %s %b %D ms</Pattern>
    </encoder>
  </appender>

  <appender-ref ref="STDOUT" />
</configuration>

访问日志将在控制台中打印为

"[ACCESS] <host> <date> "<httpmethod> <httpuri> HTTP/1.1" <httpstatus> "<timetaken in millisecond> ms""

相关问题