1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 package org.openrdf.elmo.sesame.behaviours;
30
31 import java.lang.reflect.Method;
32 import java.util.HashMap;
33 import java.util.Map;
34
35 import javax.interceptor.InvocationContext;
36
37 import org.openrdf.elmo.annotations.intercepts;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41
42
43
44
45
46
47
48 public class BeanAccessLogger {
49 private static Map<Method, Logger> loggers = new HashMap<Method, Logger>();
50
51 public static synchronized boolean interceptCondition(Method method) {
52 Logger logger = LoggerFactory.getLogger(method.getDeclaringClass());
53 if (logger.isDebugEnabled()) {
54 loggers.put(method, logger);
55 return true;
56 }
57 return false;
58 }
59
60 @intercepts(conditional="interceptCondition")
61 public Object invoke(InvocationContext ctx) throws Exception {
62 Method method = ctx.getMethod();
63 Logger logger = getLogger(method);
64 Object result;
65 try {
66 logger.debug("CALL {}#{}{}", new Object[] {
67 method.getDeclaringClass().getSimpleName(),
68 method.getName(), toString(ctx.getParameters()) });
69 result = ctx.proceed();
70 if (method.getReturnType().equals(Void.TYPE)) {
71 logger.debug("EXIT {}#{}{}",
72 new Object[] {
73 method.getDeclaringClass().getSimpleName(),
74 method.getName(),
75 toString(ctx.getParameters()) });
76 } else {
77 logger.debug("RETURN {} {}#{}{}",
78 new Object[] { trim(result),
79 method.getDeclaringClass().getSimpleName(),
80 method.getName(),
81 toString(ctx.getParameters()) });
82 }
83 return result;
84 } catch (Exception e) {
85 logger.debug("EXCEPTION "
86 + method.getDeclaringClass().getSimpleName() + '.'
87 + method.getName(), e);
88 throw e;
89 }
90 }
91
92 private String trim(Object result) {
93 String ret = String.valueOf(result);
94 if (ret.indexOf('\n') >= 0) {
95 ret = ret.replace('\n', ' ');
96 }
97 if (ret.length() > 80) {
98 ret = ret.substring(0, 39) + "..." + ret.substring(ret.length() - 38, ret.length());
99 }
100 return ret;
101 }
102
103 private String toString(Object[] a) {
104 if (a == null)
105 return "null";
106 int iMax = a.length - 1;
107 if (iMax == -1)
108 return "()";
109
110 StringBuilder b = new StringBuilder();
111 b.append('(');
112 for (int i = 0;; i++) {
113 b.append(trim(a[i]));
114 if (i == iMax)
115 return b.append(')').toString();
116 b.append(", ");
117 }
118 }
119
120 private static synchronized Logger getLogger(Method method) {
121 if (loggers.containsKey(method))
122 return loggers.get(method);
123 Logger logger = LoggerFactory.getLogger(method.getDeclaringClass());
124 loggers.put(method, logger);
125 return logger;
126 }
127 }