Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring cache logging on @Cacheable hit

Currently I am working with a Spring Cache and the @Cacheable/@CacheEvict annotations.

I would like to get some sort of a console log statement like "INFO: i got those values from the cache, NOT from the host. awesome"

Is there a clean and easy way to do this? We are using slf4j apparently btw, if that is of any interest.

like image 650
BassSultan Avatar asked May 17 '16 15:05

BassSultan


People also ask

How does @cacheable work in spring?

@CacheableThis method-level annotation lets Spring Boot know that the return value of the annotated method can be cached. Each time a method marked with this @Cacheable is called, the caching behavior will be applied.

What is the use of @cacheable annotation?

Annotation Type Cacheable. Annotation indicating that the result of invoking a method (or all methods in a class) can be cached. Each time an advised method is invoked, caching behavior will be applied, checking whether the method has been already invoked for the given arguments.

Can we use @cacheable on private method?

the caching will not be triggered. Therefore, it does not make sense to declare a private method with @Cacheable . Note that the same is true for Aspects (as suggested in the other solution); those are not triggered when calling intra-class methods either.


2 Answers

Spring itself logs some of its Caching Abstractions behaviors under the org.springframework.cache logger in trace level. So, if you append logs under the org.springframework.cache logger to an appropriate appender, you would have some useful information on, say, the console. If you're using Logback, you could use something like the following in your 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> 

With this configuration, you should see something like following on your console:

Cache entry for key 'Page request [number: 0, size 20, sort: null]' found in cache 'persons'

like image 95
Ali Dehghani Avatar answered Sep 18 '22 18:09

Ali Dehghani


And for Spring Boot 2 you can add in your application.properties:

logging.level.org.springframework.cache=TRACE 
like image 26
Rafael Renan Pacheco Avatar answered Sep 21 '22 18:09

Rafael Renan Pacheco