【问题标题】:How to use custom logger to log access log in spring bootspring boot中如何使用自定义logger记录访问日志
【发布时间】:2016-06-07 13:49:04
【问题描述】:

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

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

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

【问题讨论】:

    标签: java spring spring-boot log4j2 undertow


    【解决方案1】:

    解决这种不可自定义的硬编码问题的一个技巧是隐藏类以使用具有相同包和名称的新类退出。您所要做的就是提供一个基于 log4j 的 DefaultAccessLogReceiver 并确保它可以在 undertow 库中的类加载器之前被类加载器搜索。

    package io.undertow.server.handlers.accesslog;
    
    public class DefaultAccessLogReceiver implements AccessLogReceiver {
    
        public void logMessage(final String message) {
            // TODO: log with log4j
        }
    }
    

    【讨论】:

    • 这个想法很有趣,从来没有想过这个想法。
    • 还必须定义兼容的构造函数,它才能工作。
    【解决方案2】:

    Spring Boot 没有强制的日志依赖,除了 commons-logging API,其中有很多实现可供选择。要使用 Logback,您需要包含它,以及一些用于类路径上的 commons-logging 的绑定。最简单的方法是通过所有依赖于 spring-boot-starter-logging 的 starter pom。对于 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 pom 来组装依赖项,这意味着您必须排除 Logback,然后包含您选择的 Log4j 版本。如果您不使用 starter pom,那么除了您选择的 Log4j 版本之外,您还需要(至少)提供 commons-logging。

    最简单的路径可能是通过 starter pom,即使它需要一些与排除项的调整,.e.g.在 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。

    【讨论】:

    • 我知道这一点。但它不允许您将访问日志记录到控制台。并更改其设置。访问日志使用undertow的原生logger。
    • 您能否从您的应用程序中举例说明您到底想要做什么。在我们的应用程序中,我们可以在控制台上看到日志。
    猜你喜欢
    • 2014-06-13
    • 2014-07-22
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2017-12-26
    • 2017-11-01
    • 2021-11-19
    相关资源
    最近更新 更多