1

I have a simple spring web application, which is connected to a Postgre db. My question is I have method in dao, which is annotated with @Cacheable. Is there a way to log if the method goes to db, or its result is loaded from cache? For example, I'd like to see the following log:

The value is retrieved from db.... The value is retrieved from cache

  • 1
    Check if this answers your question - https://stackoverflow.com/questions/37281139/spring-cache-logging-on-cacheable-hit ? – Pankaj Aug 17 '20 at 18:03
  • What you really want is _metrics_; Spring Boot already integrates with Micrometer, which has support for the caching abstraction. – chrylis -cautiouslyoptimistic- Aug 17 '20 at 18:06
  • It's sounds little weird but if you want to do this then there is a way to do that. You can do that by override spring's default behaviour. Spring Internally uses `Simple Cache Resolver` to intercept the request and check if data is available in the cache for that key or not. You can override that from `SimpleCacheResolver` and if it returns the data then log your statement that you want to. – Amit Mishra Sep 25 '20 at 10:36

1 Answers1

0

You can enable trace logs for CacheAspectSupport. This is probably going to give you too much information though.

In case of a cache hit you'll get

Cache entry for key '" + key + "' found in cache '" + cache.getName() + "'"

And a cache miss

"No cache entry for key '" + key + "' in cache(s) " + context.getCacheNames()

There is no hookpoint to configure caching so that it calls you when those things happen. You may want to look at your cache library to see if they offer some hook point.

Stephane Nicoll
  • 31,977
  • 9
  • 97
  • 89