How do you tell Spring Boot to send the embedded T

2019-02-03 17:08发布

问题:

In a standalone Spring Boot web application (executable jar), how do you tell Spring Boot that we want the embedded Tomcat instance's HTTP access logs to be sent to stdout?

回答1:

If you use Logback, you can use logback-access for this.

Add dependency ch.qos.logback:logback-access

Optional Javaconfig to add TeeFilter (request & response logging):

@Bean(name = "TeeFilter")
public Filter teeFilter() {
    return new ch.qos.logback.access.servlet.TeeFilter();
}

Javaconfig for embedded tomcat:

@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();

    // put logback-access.xml in src/main/resources/conf
    tomcat.addContextValves(new LogbackValve());

    return tomcat;
}

Contents for logback-access.xml (save in src/main/resources/conf)

<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <Pattern>combined</Pattern>
      <Pattern>%fullRequest%n%n%fullResponse</Pattern>
    </encoder>
  </appender>

  <appender-ref ref="STDOUT" />

</configuration>


回答2:

This did it for me on Spring Boot 2.x:

server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.directory=/dev
server.tomcat.accesslog.prefix=stdout
server.tomcat.accesslog.buffered=false
server.tomcat.accesslog.suffix=""
server.tomcat.accesslog.file-date-format=""


回答3:

Here's the followup up on the great answer from JohanB, for Spring Boot 2.0.0+.

In Spring Boot 2.0.0, the EmbeddedServletContainerFactory was replaced with TomcatServletWebServerFactory. All other aspects of JohanB's answer still works correctly the factory bean creation just needs to be modified:

@Bean
public TomcatServletWebServerFactory servletContainer() {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
    // put logback-access.xml in src/main/resources/conf
    tomcat.addContextValves(new LogbackValve());
    return tomcat;
}