View Javadoc
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  
18  import org.apache.ibatis.cache.Cache;
19  import org.apache.ibatis.logging.Log;
20  import org.apache.ibatis.logging.LogFactory;
21  
22  /**
23   * @author Clinton Begin
24   */
25  public class LoggingCache implements Cache {
26  
27    private final Log log;
28    private final Cache delegate;
29    protected int requests;
30    protected int hits;
31  
32    public LoggingCache(Cache delegate) {
33      this.delegate = delegate;
34      this.log = LogFactory.getLog(getId());
35    }
36  
37    @Override
38    public String getId() {
39      return delegate.getId();
40    }
41  
42    @Override
43    public int getSize() {
44      return delegate.getSize();
45    }
46  
47    @Override
48    public void putObject(Object key, Object object) {
49      delegate.putObject(key, object);
50    }
51  
52    @Override
53    public Object getObject(Object key) {
54      requests++;
55      final Object value = delegate.getObject(key);
56      if (value != null) {
57        hits++;
58      }
59      if (log.isDebugEnabled()) {
60        log.debug("Cache Hit Ratio [" + getId() + "]: " + getHitRatio());
61      }
62      return value;
63    }
64  
65    @Override
66    public Object removeObject(Object key) {
67      return delegate.removeObject(key);
68    }
69  
70    @Override
71    public void clear() {
72      delegate.clear();
73    }
74  
75    @Override
76    public int hashCode() {
77      return delegate.hashCode();
78    }
79  
80    @Override
81    public boolean equals(Object obj) {
82      return delegate.equals(obj);
83    }
84  
85    private double getHitRatio() {
86      return (double) hits / (double) requests;
87    }
88  
89  }