1
2
3
4
5 package org.neo.swarm.interceptor.logging;
6
7 import java.lang.reflect.InvocationTargetException;
8 import java.lang.reflect.UndeclaredThrowableException;
9 import java.util.HashMap;
10 import java.util.logging.Level;
11 import java.util.logging.Logger;
12
13 import org.aopalliance.intercept.MethodInvocation;
14 import org.neo.swarm.core.aop.silc.comp.MethodInterceptor;
15 import org.neo.swarm.util.serialize.Serializer;
16 import org.neo.swarm.util.serialize.XMLSerializer;
17
18
19 /***
20 *
21 * @author navery
22 */
23 public class JavaLoggingInterceptor implements MethodInterceptor {
24 static HashMap loggers = new HashMap();
25 static Serializer serializer = new XMLSerializer();
26 static boolean enabled = false;
27
28 /***
29 *
30 */
31 public JavaLoggingInterceptor(boolean enableLogging) {
32 enabled = enableLogging;
33 }
34
35
36
37
38 public Object invoke(MethodInvocation invocation) throws Throwable {
39 if (!enabled) return invocation.proceed();
40
41 Logger log = getLogger(invocation.getClass());
42 try {
43 String invocationString = invocation.toString();
44 log.info(">>" + invocationString);
45 Object ret = invocation.proceed();
46 log.info("<<" + invocationString + ret);
47 return ret;
48 } catch (Exception ex) {
49 if (serializer == null ) serializer = new XMLSerializer();
50 log.warning("===============LOGGER REPORTING EXCEPTION ===================");
51 log.warning("Invocation:" + new String(serializer.serialize(invocation)));
52 log.warning(" Cause: "+ new String(serializer.serialize(ex)));
53 log.log(Level.SEVERE, "Exception:", ex);
54 if (ex instanceof InvocationTargetException) {
55 InvocationTargetException ex2 = (InvocationTargetException) ex;
56 if (ex2.getTargetException() instanceof UndeclaredThrowableException) {
57 UndeclaredThrowableException ex3 = (UndeclaredThrowableException) ex2.getTargetException();
58 Exception ex4 = (Exception) ex3.getUndeclaredThrowable();
59 log.log(Level.SEVERE, "RealCause: " + ex4 + " msg: "+ ex4.getMessage(), ex4);
60 throw ex4;
61 }
62 }
63 throw ex;
64 }
65 }
66
67 protected Logger getLogger(Class clazz){
68 Logger log = (Logger) loggers.get(clazz);
69 if (log == null) {
70 log = Logger.getLogger(clazz.toString());
71 loggers.put(clazz, log);
72 }
73 return log;
74 }
75 }