| 1 7 package com.tirsen.nanning.samples; 8 9 import com.tirsen.nanning.Invocation; 10 import com.tirsen.nanning.MethodInterceptor; 11 import com.tirsen.nanning.definition.SingletonInterceptor; 12 import org.apache.commons.logging.Log; 13 import org.apache.commons.logging.LogFactory; 14 15 23 public class TraceInterceptor implements MethodInterceptor, SingletonInterceptor { 24 private Log logger; 25 26 public TraceInterceptor(Log logger) { 27 this.logger = logger; 28 } 29 30 public TraceInterceptor() { 31 } 32 33 public Object invoke(Invocation invocation) throws Throwable { 34 StopWatch watch = new StopWatch(false); 35 36 Log logger = getLogger(invocation.getTarget().getClass()); 37 38 StringBuffer methodCallMessage = new StringBuffer (); 39 methodCallMessage.append(invocation.getMethod().getName()); 40 methodCallMessage.append('('); 41 Object [] args = invocation.getArgs(); 42 if (args != null) { 43 for (int i = 0; i < args.length; i++) { 44 Object arg = args[i]; 45 methodCallMessage.append(arg); 46 if (i + 1 < args.length) { 47 methodCallMessage.append(", "); 48 } 49 } 50 } 51 methodCallMessage.append(')'); 52 logger.debug(">>> " + methodCallMessage); 53 Object result = null; 54 try { 55 result = invocation.invokeNext(); 56 return result; 57 } catch (Throwable e) { 58 watch.stop(); 59 logger.error("<<< " + methodCallMessage + " threw exception, took " + (int) watch.getTimeSpent() + " ms", e); 60 throw e; 61 } finally { 62 watch.stop(); 63 logger.debug("<<< " + methodCallMessage + ", took " + (int) watch.getTimeSpent() + " ms, result " + result); 64 } 65 } 66 67 private Log getLogger(Class targetClass) { 68 Log logger; 69 logger = this.logger; 70 if (logger == null) { 71 logger = LogFactory.getLog(targetClass); 72 } 73 return logger; 74 } 75 } 76 | Popular Tags |