1 17 package org.apache.servicemix.sca.tuscany; 18 19 import java.lang.ref.WeakReference ; 20 import java.lang.reflect.InvocationHandler ; 21 import java.lang.reflect.Method ; 22 import java.lang.reflect.Proxy ; 23 import java.util.Map ; 24 import java.util.WeakHashMap ; 25 26 import org.apache.commons.logging.Log; 27 import org.apache.commons.logging.LogFactory; 28 import org.apache.tuscany.common.monitor.MonitorFactory; 29 30 public class CommonsLoggingMonitorFactory implements MonitorFactory { 31 32 private final Map <Class <?>, WeakReference <?>> proxies = new WeakHashMap <Class <?>, WeakReference <?>>(); 33 34 public CommonsLoggingMonitorFactory() { 35 } 36 37 public <T> T getMonitor(Class <T> monitorInterface) { 38 T proxy = getCachedMonitor(monitorInterface); 39 if (proxy == null) { 40 proxy = createMonitor(monitorInterface); 41 proxies.put(monitorInterface, new WeakReference <T>(proxy)); 42 } 43 return proxy; 44 } 45 46 private <T>T getCachedMonitor(Class <T> monitorInterface) { 47 WeakReference <T> ref = (WeakReference <T>) proxies.get(monitorInterface); 48 return (ref != null) ? ref.get() : null; 49 } 50 51 private <T>T createMonitor(Class <T> monitorInterface) { 52 String className = monitorInterface.getName(); 53 Log logger = LogFactory.getLog(className); 54 InvocationHandler handler = new LoggingHandler(logger); 55 return (T) Proxy.newProxyInstance(monitorInterface.getClassLoader(), new Class <?>[]{monitorInterface}, handler); 56 } 57 58 private static final class LoggingHandler implements InvocationHandler { 59 private final Log logger; 60 61 public LoggingHandler(Log logger) { 62 this.logger = logger; 63 } 64 65 public Object invoke(Object proxy, Method method, Object [] args) throws Throwable { 66 String sourceMethod = method.getName(); 67 if (logger.isDebugEnabled()) { 68 if (args != null && args.length == 1 && args[0] instanceof Throwable ) { 70 logger.debug(sourceMethod, (Throwable ) args[0]); 71 } else { 72 StringBuilder sb = new StringBuilder (); 73 sb.append(sourceMethod); 74 sb.append("("); 75 for (int i = 0; i < args.length; i++) { 76 if (i > 0) { 77 sb.append(", "); 78 } 79 sb.append(args[i]); 80 } 81 sb.append(")"); 82 logger.debug(sb.toString()); 83 } 84 } 85 return null; 86 } 87 } 88 } 89 | Popular Tags |