如何在spring-boot中配置tomcat访问日志的位置和名称?

How do I configure the location and name of tomcat access log in spring-boot?

我有一个 spring-boot 应用程序,在 application.yml

中具有以下配置
server:
contextPath: /rti
tomcat:
    access-log-enabled: true
    access-log-pattern: "%h %l %u %t \"%r\" %s %b %D"
    basedir: tomcat

这会提示创建访问日志tomcat/logs/access_log.2015-02-12.txt.

我希望能够配置访问日志的创建位置和命名;但经过大量搜索后,我开始认为这是不可能的。有人知道如何实现这一目标吗?

应用程序日志记录在 logback.xml

中使用 logback 和配置工作正常

您可以使用 EmbeddedServletContainerCustomizer 接口将完全自定义的阀添加到您的嵌入式 tomcat。这对我有用:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        if (container instanceof TomcatEmbeddedServletContainerFactory) {
            TomcatEmbeddedServletContainerFactory factory = (TomcatEmbeddedServletContainerFactory) container;
            AccessLogValve accessLogValve = new AccessLogValve();
            accessLogValve.setDirectory("/var/log/test");
            accessLogValve.setPattern("common");
            accessLogValve.setSuffix(".log");
            factory.addContextValves(accessLogValve);
        } else {
            logger.error("WARNING! this customizer does not support your configured container");
        }
    }

}

配置使用 application.yml (https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html):

server.tomcat.accesslog:
  # Enable access log:
  enabled: true

  # Directory in which log files are created. Can be relative to the tomcat base dir or absolute:
  directory: /var/log/test 

  # Format pattern for access logs:
  # https://tomcat.apache.org/tomcat-8.0-doc/config/valve.html#Access_Log_Valve
  pattern: "%h %l %u %t "%r" %s %b %D"

  # Log file name suffix:
  suffix: ".log"

如果您使用 application.yml 进行配置。

你可以参考这个:

server:
  tomcat:
    basedir: tomcat/
    accesslog:
      enabled: true
      prefix: access-log
      suffix: .log
      # datetime remote-ip "request-referr" status (time-taken) 
      pattern: '%t %a "%r" %s %D'

您将生成一个名称类似于 access-log.2018.08.22.log 的文件。日志格式为

[22/Aug/2018:16:00:34 +0800] 0:0:0:0:0:0:0:1 "GET /search-query/video/123 HTTP/1.1" 200 666

在上面的示例中,日志将在相对于应用程序工作目录的 tomcat/logs 中可用。

您可以设置此项来更改您的日志文件名:

server:
  tomcat:
    accesslog:
      prefix: access
      file-date-format: .yyyy-MM-dd
      suffix: .log

那么日志格式将是:access.2018-08-22.log

如果要自定义日志格式,可以更新 pattern

有两种内部模式:

server.tomcat.accesslog.pattern=common

server.tomcat.accesslog.pattern=combined

参考这里了解更多信息:https://tomcat.apache.org/tomcat-8.0-doc/config/valve.html#Access_Logging