如何使用自定义记录器记录访问登录 spring 启动

How to use custom logger to log access log in spring boot

目前在spring boot 1.3 中,我们只能将访问日志记录到文件系统中的文件中。有什么方法可以实际使用自定义记录器(如 log4j2)来记录访问日志?

我目前在 spring 引导下使用 undertow,但在检查 spring 引导源代码后,undertow 记录器使用正在写入文件的 DefaultAccessLogReceiver 初始化。如果可能,我想使用 AccessLogHandler,并避免编写记录访问的 Web 过滤器。

有什么简单的方法可以解决这个问题吗? (除了写拉取请求)

Spring Boot 没有强制的日志记录依赖,除了 commons-logging API,它有很多实现可供选择。要使用 Logback,您需要包含它,以及类路径上的公共日志记录的一些绑定。最简单的方法是通过 starter poms,它都依赖于 spring-boot-starter-logging。对于 Web 应用程序,您只需要 spring-boot-starter-web 因为它传递地依赖于日志记录启动器。例如,使用 Maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Spring Boot 有一个 LoggingSystem 抽象,它尝试根据类路径的内容配置日志记录。如果 Logback 可用,它是首选。

Spring Boot 还支持 Log4j 或 Log4j 2 用于日志记录配置,但前提是其中之一在类路径上。如果您使用 starter poms 来组装依赖项,这意味着您必须排除 Logback,然后包括您选择的 Log4j 版本。如果您不使用入门 poms,那么除了您选择的 Log4j 版本之外,您还需要提供 commons-logging(至少)。

最简单的路径可能是通过 starter poms,尽管它需要一些排除项,例如在 Maven 中:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j</artifactId>
</dependency>

要使用 Log4j 2,只需依赖 spring-boot-starter-log4j2 而不是 spring-boot-starter-log4j。

解决这种硬编码因此不可定制的问题的一个技巧是隐藏 class 以用具有相同包和名称的新问题踢出。您所要做的就是提供一个基于 DefaultAccessLogReceiver 的 log4j 并确保它可以被 classloader 在 undertow 库中的那个之前搜索。

package io.undertow.server.handlers.accesslog;

public class DefaultAccessLogReceiver implements AccessLogReceiver {

    public void logMessage(final String message) {
        // TODO: log with log4j
    }
}