Spring 在@Cacheable 命中时缓存日志记录
Spring cache logging on @Cacheable hit
目前我正在使用 Spring 缓存和 @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
:
中使用类似以下内容
<?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>
使用此配置,您应该会在控制台上看到如下内容:
Cache entry for key 'Page request [number: 0, size 20, sort: null]'
found in cache 'persons'
您可以启用跟踪级别日志记录。
例如,在 application.properties 中输入 'trace=true'.
对于 Spring Boot 2,您可以添加 application.properties:
logging.level.org.springframework.cache=TRACE
我不认为一直打开跟踪日志是个好主意,即使它只用于缓存日志。
更好的方法是,EHcache 已经有这个 hit/miss 指标,你可以通过 JMX
或 spring boot actuator
.
来获取它
JMX使用,可参考this
要使用Spring Boot Actuator
,可以参考this。
目前我正在使用 Spring 缓存和 @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
:
<?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>
使用此配置,您应该会在控制台上看到如下内容:
Cache entry for key 'Page request [number: 0, size 20, sort: null]' found in cache 'persons'
您可以启用跟踪级别日志记录。
例如,在 application.properties 中输入 'trace=true'.
对于 Spring Boot 2,您可以添加 application.properties:
logging.level.org.springframework.cache=TRACE
我不认为一直打开跟踪日志是个好主意,即使它只用于缓存日志。
更好的方法是,EHcache 已经有这个 hit/miss 指标,你可以通过 JMX
或 spring boot actuator
.
JMX使用,可参考this
要使用Spring Boot Actuator
,可以参考this。