【问题标题】:Spring cache logging on @Cacheable hit@Cacheable 命中的 Spring 缓存日志记录
【发布时间】:2016-09-13 20:23:37
【问题描述】:

目前我正在使用 Spring Cache 和 @Cacheable/@CacheEvict 注释。

我想获得某种控制台日志语句,例如 "INFO: i got those values from the cache, NOT from the host. awesome"

有没有一种干净简单的方法来做到这一点?顺便说一句,我们正在使用slf4j,如果有任何兴趣的话。

【问题讨论】:

    标签: java spring slf4j spring-cache


    【解决方案1】:

    Spring 本身在org.springframework.cache 记录器的trace 级别下记录了它的一些缓存抽象行为。因此,如果您将 org.springframework.cache 记录器下的日志附加到适当的附加程序,您将获得一些有用的信息,例如控制台。如果您使用 Logback,您可以在 logback.xml 中使用类似以下内容:

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>%msg%n</pattern>
            </encoder>
        </appender>
    
        <logger name="org.springframework.cache" level="trace">
            <appender-ref ref="STDOUT" />
        </logger>
    </configuration>
    

    使用此配置,您应该会在控制台上看到类似以下内容:

    键 'Page request [number: 0, size 20, sort: null]' 的缓存条目 在缓存“人员”中找到

    【讨论】:

    • 这帮助我在我们的项目设置中找到了类似的配置。谢谢:)
    【解决方案2】:

    对于 Spring Boot 2,您可以在 application.properties 中添加:

    logging.level.org.springframework.cache=TRACE
    

    【讨论】:

      【解决方案3】:

      您可以启用跟踪级别日志记录。

      例如,在 application.properties 中输入 'trace=true'。

      Spring logging documentation

      【讨论】:

        【解决方案4】:

        我不认为一直打开跟踪日志是一个好主意,即使它只是用于缓存日志。
        更好的方法是,EHcache 已经有这个命中/未命中指标,你可以通过JMXspring boot actuator 获得。

        JMX使用可以参考this

        要使用Spring Boot Actuator,可以参考this

        【讨论】:

        • 绝对同意,除非它会在本地开发人员机器上完成。然而,这是非常好的和有价值的提示,如何记录和监控缓存行为。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-07
        • 2018-04-13
        • 1970-01-01
        • 2019-07-15
        • 2016-10-23
        • 2020-02-27
        • 1970-01-01
        相关资源
        最近更新 更多