View Javadoc

1   package com.github.sfleiter.cdi_interceptors;
2   
3   import java.lang.annotation.Annotation;
4   import java.lang.reflect.Method;
5   
6   import javax.inject.Inject;
7   import javax.interceptor.AroundInvoke;
8   import javax.interceptor.Interceptor;
9   import javax.interceptor.InvocationContext;
10  
11  import uk.org.lidalia.slf4jext.Level;
12  import uk.org.lidalia.slf4jext.Logger;
13  import uk.org.lidalia.slf4jext.LoggerFactory;
14  
15  import com.github.sfleiter.cdi_interceptors.impl.StringTransformer;
16  import com.thoughtworks.paranamer.AdaptiveParanamer;
17  import com.thoughtworks.paranamer.BytecodeReadingParanamer;
18  import com.thoughtworks.paranamer.CachingParanamer;
19  import com.thoughtworks.paranamer.Paranamer;
20  import com.thoughtworks.paranamer.PositionalParanamer;
21  
22  /**
23   * The Class LoggingInterceptor add a special kind of logging advice to classes
24   * / methods. Calls with parameter names, results and exceptions are logged in a
25   * single line.
26   * 
27   * A {@link BytecodeReadingParanamer} is use to detect parameter names. If
28   * paranamer does not deliver names, a default of arg0...n is used.
29   * 
30   * @see Logging
31   */
32  @Interceptor
33  @Logging
34  public class LoggingInterceptor {
35  
36      /** The paranamer used to get parameter names. */
37      private final Paranamer paranamer = new CachingParanamer(
38              new AdaptiveParanamer(
39                      new BytecodeReadingParanamer(),
40                      new PositionalParanamer()
41                      ));
42  
43      @Inject
44      private StringTransformer stringTransformer;
45  
46      /**
47       * Logging method invoke.
48       * 
49       * @param ctx
50       *            the invocation context
51       * @return the result object
52       * @throws Exception
53       *             only rethrows original exception from intercepted method call
54       */
55      @AroundInvoke
56      public Object loggingMethodInvoke(final InvocationContext ctx) throws Exception {
57          Logger logger = LoggerFactory.getLogger(ctx.getTarget().getClass()
58                  .getName());
59          Logging annotation = getAnnotation(ctx.getMethod(), Logging.class);
60          Level level = annotation.standardLogLevel();
61          int maximumCount = annotation.logItemLimit();
62          boolean measureDuration = annotation.measureDuration();
63  
64          StringBuilder sb;
65          long start = currentTimeMillis(measureDuration);
66          long duration;
67          Object result;
68          try {
69              result = ctx.proceed();
70              if (logger.isEnabled(level)) {
71                  duration = currentTimeMillis(measureDuration) - start;
72                  sb = getCallString(ctx, maximumCount);
73                  sb.append(" returns ");
74                  stringTransformer.transform(sb, result, maximumCount);
75                  appendDuration(sb, measureDuration, duration);
76                  logger.log(level, sb.toString());
77              }
78          } catch (Exception e) {
79              if (e instanceof RuntimeException) {
80                  level = annotation.severeExceptionLogLevel();
81              }
82              if (logger.isEnabled(level)) {
83                  duration = currentTimeMillis(measureDuration) - start;
84                  sb = getCallString(ctx, maximumCount);
85                  sb.append(" caused ");
86                  sb.append(e.getMessage());
87                  appendDuration(sb, measureDuration, duration);
88                  logger.log(level, sb.toString(), e);
89              }
90              throw e;
91          }
92          return result;
93      }
94  
95      /**
96       * Searches an annotation at the specified method of class and if not found
97       * there at the respective class. This method can be used to to query the
98       * annotations parameters.
99       * 
100      * @param method
101      *            the method to search at
102      * @param annotationClazz
103      *            the annotation to search
104      * @param <T>
105      *            the type of the annotation
106      * @return found annotation
107      * @throws RuntimeException
108      *             if annotation is not found
109      */
110     private <T extends Annotation> T getAnnotation(final Method method, final Class<T> annotationClazz)
111             throws RuntimeException {
112         // first look at method-level annotations, since they take priority
113         for (Annotation a : method.getAnnotations()) {
114             if (annotationClazz.isInstance(a)) {
115                 return annotationClazz.cast(a);
116             }
117         }
118         for (Annotation a : method.getDeclaringClass().getAnnotations()) {
119             if (annotationClazz.isInstance(a)) {
120                 return annotationClazz.cast(a);
121             }
122         }
123         throw new RuntimeException("@" + annotationClazz.getName() + " not found on method " + method.getName()
124                 + " or its class " + method.getClass().getName());
125     }
126 
127     /**
128      * Creates a string representation of the method call including method name
129      * and parameter representation.
130      * 
131      * @param ctx
132      *            the InvocationContext
133      * @param maximumCount
134      *            maximum count of object to to represent per collection or
135      *            array instance
136      * @return StringBuilder with string describing call
137      */
138     private StringBuilder getCallString(final InvocationContext ctx, final int maximumCount) {
139         StringBuilder sb = new StringBuilder();
140         sb.append("call ");
141         sb.append(ctx.getMethod().getName());
142         sb.append("(");
143         Object[] parameters = ctx.getParameters();
144         String[] parameterNames = paranamer.lookupParameterNames(
145                 ctx.getMethod(), false);
146         for (int i = 0; i < parameters.length; i++) {
147             sb.append(parameterNames[i]);
148             sb.append("=");
149             stringTransformer.transform(sb, parameters[i], maximumCount);
150             if (i < parameterNames.length - 1) {
151                 sb.append(", ");
152             }
153         }
154         sb.append(")");
155         return sb;
156     }
157 
158     /**
159      * Returns current system time or 0 if measurement is deactivated.
160      * 
161      * @param measureDuration
162      *            true if duration measurement should be active
163      * @return current time in millis or 0
164      */
165     private long currentTimeMillis(final boolean measureDuration) {
166         return measureDuration ? System.currentTimeMillis() : 0;
167     }
168 
169     /**
170      * Appends the duration of the call.
171      * 
172      * @param sb
173      *            the StringBuilder to append to
174      * @param measureDuration
175      *            true if measurement and appending should take place
176      * @param duration
177      *            time taken for call in milliseconds
178      */
179     private void appendDuration(final StringBuilder sb, final boolean measureDuration, final long duration) {
180         if (measureDuration) {
181             sb.append(" [duration=");
182             sb.append(duration);
183             sb.append("ms]");
184         }
185     }
186 
187 }