1
2
3
4
5
6
7
8
9
10
11 package psiprobe.tools.logging.jdk;
12
13 import java.lang.reflect.InvocationTargetException;
14 import java.lang.reflect.Method;
15 import java.util.ArrayList;
16 import java.util.Collections;
17 import java.util.Enumeration;
18 import java.util.List;
19
20 import org.apache.commons.lang3.reflect.MethodUtils;
21
22 import psiprobe.tools.logging.DefaultAccessor;
23 import psiprobe.tools.logging.LogDestination;
24
25
26
27
28 public class Jdk14ManagerAccessor extends DefaultAccessor {
29
30
31
32
33
34
35
36
37
38
39 public Jdk14ManagerAccessor(ClassLoader cl)
40 throws ClassNotFoundException, IllegalAccessException, InvocationTargetException {
41
42 Class<?> clazz = cl.loadClass("java.util.logging.LogManager");
43 Method getManager = MethodUtils.getAccessibleMethod(clazz, "getLogManager");
44 Object manager = getManager.invoke(null);
45 if (manager == null) {
46 throw new NullPointerException(clazz.getName() + ".getLogManager() returned null");
47 }
48 setTarget(manager);
49 }
50
51
52
53
54
55
56 public Jdk14LoggerAccessor getRootLogger() {
57 return getLogger("");
58 }
59
60
61
62
63
64
65
66
67 public Jdk14LoggerAccessor getLogger(String name) {
68 try {
69 Object logger = MethodUtils.invokeMethod(getTarget(), "getLogger", name);
70 if (logger == null) {
71 throw new NullPointerException(
72 getTarget().getClass().getName() + "#getLogger(\"" + name + "\") returned null");
73 }
74 Jdk14LoggerAccessor accessor = new Jdk14LoggerAccessor();
75 accessor.setTarget(logger);
76 accessor.setApplication(getApplication());
77 return accessor;
78 } catch (Exception e) {
79 logger.error("{}#getLogger('{}') failed", getTarget().getClass().getName(), name, e);
80 }
81 return null;
82 }
83
84
85
86
87
88
89 @SuppressWarnings("unchecked")
90 public List<LogDestination> getHandlers() {
91 List<LogDestination> allHandlers = new ArrayList<>();
92 try {
93 for (String name : Collections
94 .list((Enumeration<String>) MethodUtils.invokeMethod(getTarget(), "getLoggerNames"))) {
95 Jdk14LoggerAccessor accessor = getLogger(name);
96 if (accessor != null) {
97 allHandlers.addAll(accessor.getHandlers());
98 }
99 }
100 } catch (Exception e) {
101 logger.error("{}#getLoggerNames() failed", getTarget().getClass().getName(), e);
102 }
103 return allHandlers;
104 }
105
106 }