LoggingCache.java

  1. /*
  2.  *    Copyright 2009-2023 the original author or authors.
  3.  *
  4.  *    Licensed under the Apache License, Version 2.0 (the "License");
  5.  *    you may not use this file except in compliance with the License.
  6.  *    You may obtain a copy of the License at
  7.  *
  8.  *       https://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  *    Unless required by applicable law or agreed to in writing, software
  11.  *    distributed under the License is distributed on an "AS IS" BASIS,
  12.  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  *    See the License for the specific language governing permissions and
  14.  *    limitations under the License.
  15.  */
  16. package org.apache.ibatis.cache.decorators;

  17. import org.apache.ibatis.cache.Cache;
  18. import org.apache.ibatis.logging.Log;
  19. import org.apache.ibatis.logging.LogFactory;

  20. /**
  21.  * @author Clinton Begin
  22.  */
  23. public class LoggingCache implements Cache {

  24.   private final Log log;
  25.   private final Cache delegate;
  26.   protected int requests;
  27.   protected int hits;

  28.   public LoggingCache(Cache delegate) {
  29.     this.delegate = delegate;
  30.     this.log = LogFactory.getLog(getId());
  31.   }

  32.   @Override
  33.   public String getId() {
  34.     return delegate.getId();
  35.   }

  36.   @Override
  37.   public int getSize() {
  38.     return delegate.getSize();
  39.   }

  40.   @Override
  41.   public void putObject(Object key, Object object) {
  42.     delegate.putObject(key, object);
  43.   }

  44.   @Override
  45.   public Object getObject(Object key) {
  46.     requests++;
  47.     final Object value = delegate.getObject(key);
  48.     if (value != null) {
  49.       hits++;
  50.     }
  51.     if (log.isDebugEnabled()) {
  52.       log.debug("Cache Hit Ratio [" + getId() + "]: " + getHitRatio());
  53.     }
  54.     return value;
  55.   }

  56.   @Override
  57.   public Object removeObject(Object key) {
  58.     return delegate.removeObject(key);
  59.   }

  60.   @Override
  61.   public void clear() {
  62.     delegate.clear();
  63.   }

  64.   @Override
  65.   public int hashCode() {
  66.     return delegate.hashCode();
  67.   }

  68.   @Override
  69.   public boolean equals(Object obj) {
  70.     return delegate.equals(obj);
  71.   }

  72.   private double getHitRatio() {
  73.     return (double) hits / (double) requests;
  74.   }

  75. }