簡體   English   中英

@Cacheable 命中的 Spring 緩存日志記錄

[英]Spring cache logging on @Cacheable hit

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

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

有沒有一種干凈簡單的方法來做到這一點? 順便說一句,我們顯然正在使用slf4j ,如果有任何興趣的話。

Spring 本身在trace級別的org.springframework.cache記錄器下記錄了它的一些緩存抽象行為。 因此,如果您將org.springframework.cache記錄器下的日志附加到適當的附加程序,您將獲得一些關於控制台的有用信息。 如果您使用的是 Logback,則可以在logback.xml使用以下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>

使用此配置,您應該會在控制台上看到類似以下內容:

在緩存 'persons' 中找到鍵 'Page request [number: 0, size 20, sort: null]' 的緩存條目

對於 Spring Boot 2,您可以在 application.properties 中添加:

logging.level.org.springframework.cache=TRACE

您可以啟用跟蹤級別日志記錄。

例如,在 application.properties 中放置 'trace=true'。

Spring日志記錄文檔

我不認為一直打開跟蹤日志是一個好主意,即使它只用於緩存日志。
更好的方法是,EHcache 已經有了這個命中/未命中指標,你可以通過JMXspring boot actuator獲取它。

要由 JMX 使用,您可以參考這個

要使用Spring Boot Actuator ,你可以參考這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM