1
2
3
4
5
6
7
8
9
10
11 package psiprobe.tools.logging.logback;
12
13 import java.lang.reflect.InvocationTargetException;
14 import java.lang.reflect.Method;
15 import java.util.ArrayList;
16 import java.util.List;
17
18 import org.apache.commons.lang3.reflect.MethodUtils;
19
20 import psiprobe.tools.logging.DefaultAccessor;
21
22
23
24
25
26
27
28
29
30
31
32
33 public class LogbackFactoryAccessor extends DefaultAccessor {
34
35
36
37
38
39
40
41
42
43
44 public LogbackFactoryAccessor(ClassLoader cl)
45 throws ClassNotFoundException, IllegalAccessException, InvocationTargetException {
46
47
48 Class<?> clazz = cl.loadClass("org.slf4j.impl.StaticLoggerBinder");
49 Method getSingleton = MethodUtils.getAccessibleMethod(clazz, "getSingleton");
50 Object singleton = getSingleton.invoke(null);
51 Method getLoggerFactory = MethodUtils.getAccessibleMethod(clazz, "getLoggerFactory");
52
53 Object loggerFactory = getLoggerFactory.invoke(singleton);
54
55
56 Class<?> loggerFactoryClass = cl.loadClass("ch.qos.logback.classic.LoggerContext");
57 if (!loggerFactoryClass.isInstance(loggerFactory)) {
58 throw new RuntimeException("The singleton SLF4J binding was not Logback");
59 }
60 setTarget(loggerFactory);
61 }
62
63
64
65
66
67
68 public LogbackLoggerAccessor getRootLogger() {
69
70
71 return getLogger("ROOT");
72 }
73
74
75
76
77
78
79
80
81 public LogbackLoggerAccessor getLogger(String name) {
82 try {
83 Class<? extends Object> clazz = getTarget().getClass();
84 Method getLogger = MethodUtils.getAccessibleMethod(clazz, "getLogger", String.class);
85
86 Object logger = getLogger.invoke(getTarget(), name);
87 if (logger == null) {
88 throw new NullPointerException(getTarget() + ".getLogger(\"" + name + "\") returned null");
89 }
90 LogbackLoggerAccessor accessor = new LogbackLoggerAccessor();
91 accessor.setTarget(logger);
92 accessor.setApplication(getApplication());
93 return accessor;
94
95 } catch (Exception e) {
96 logger.error("{}.getLogger('{}') failed", getTarget(), name, e);
97 }
98 return null;
99 }
100
101
102
103
104
105
106 @SuppressWarnings("unchecked")
107 public List<LogbackAppenderAccessor> getAppenders() {
108 List<LogbackAppenderAccessor> appenders = new ArrayList<>();
109 try {
110 Class<? extends Object> clazz = getTarget().getClass();
111 Method getLoggerList = MethodUtils.getAccessibleMethod(clazz, "getLoggerList");
112
113 List<Object> loggers = (List<Object>) getLoggerList.invoke(getTarget());
114 for (Object logger : loggers) {
115 LogbackLoggerAccessor accessor = new LogbackLoggerAccessor();
116 accessor.setTarget(logger);
117 accessor.setApplication(getApplication());
118
119 appenders.addAll(accessor.getAppenders());
120 }
121 } catch (Exception e) {
122 logger.error("{}.getLoggerList() failed", getTarget(), e);
123 }
124 return appenders;
125 }
126
127 }