你如何告诉Spring Boot将嵌入式Tomcat的访问日志发送到stdout?

Les*_*ood 8 logging tomcat stdout spring-boot

在一个独立的Spring Boot Web应用程序(可执行jar)中,您如何告诉Spring Boot我们希望将嵌入式Tomcat实例的HTTP访问日志发送到stdout?

Joh*_*anB 12

如果使用Logback,则可以使用logback-access.

添加依赖项 ch.qos.logback:logback-access

可选的Javaconfig添加TeeFilter(请求和响应日志记录):

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

嵌入式tomcat的Javaconfig:

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

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

    return tomcat;
}
Run Code Online (Sandbox Code Playgroud)

内容logback-access.xml(保存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>
Run Code Online (Sandbox Code Playgroud)


Seb*_*ian 7

更新2019.02.11:

这些墨水应有助于映射应在application.properties以下属性中设置的属性:


@acohen的答案是正确的。如果提供空的双引号将不起作用。我将扩展他的答案,因为我认为这对于不希望添加依赖项或修改代码的人很重要:

config / application.properties

# here we say that we want to enable accesslog
server.tomcat.accesslog.enabled=true

# it is important to understand what the options means:
# 'directory/prefix + suffix + file-date-format' will be
# the file that tomcat will try to open.
# /dev/stdout is standard output, so we want tomcat
# to write to that fd. Then, we need to play with
# directory, prefix, suffix and file-date-format to match our desired path.
server.tomcat.accesslog.directory=/dev
server.tomcat.accesslog.prefix=stdout
server.tomcat.accesslog.buffered=false

# Don't use empty double quotes, see below
server.tomcat.accesslog.suffix=
server.tomcat.accesslog.file-date-format=

Run Code Online (Sandbox Code Playgroud)

笔记

  1. 如果设置file-date-formatsuffix是双引号,你都会有这样的错误:
java.io.FileNotFoundException: /dev/stdout"""" (Permission denied)

Run Code Online (Sandbox Code Playgroud)
  1. 如果不将它们包含在配置文件中,则将使用默认值,并且会出现以下错误:
java.io.FileNotFoundException: /dev/stdout.2019-02-07.log (Permission denied)
Run Code Online (Sandbox Code Playgroud)
  1. 如果您将它们留空,那么它将起作用。


aco*_*hen 5

这是在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=""
Run Code Online (Sandbox Code Playgroud)