1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.allanbank.mongodb.util.log;
21
22 import java.lang.reflect.InvocationTargetException;
23 import java.lang.reflect.Method;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26
27
28
29
30
31
32
33
34 public class Slf4jLogFactory extends LogFactory {
35
36 private final Class<?> myLocationAwareLoggerClass;
37
38
39
40
41
42 private final Method myLogFactoryMethod;
43
44
45
46
47
48 private final Method myLogMethod;
49
50
51
52
53
54
55
56 public Slf4jLogFactory() throws RuntimeException {
57 Class<?> logFactoryClass;
58 try {
59 logFactoryClass = Class.forName("org.slf4j.LoggerFactory");
60 }
61 catch (final ClassNotFoundException e) {
62
63 throw new RuntimeException(e);
64 }
65
66 try {
67 myLogFactoryMethod = logFactoryClass.getMethod("getLogger",
68 Class.class);
69
70 myLocationAwareLoggerClass = Class
71 .forName("org.slf4j.spi.LocationAwareLogger");
72 final Class<?> markerClass = Class.forName("org.slf4j.Marker");
73 myLogMethod = myLocationAwareLoggerClass.getMethod("log",
74 markerClass, String.class, int.class, String.class,
75 Object[].class, Throwable.class);
76 }
77 catch (final ClassNotFoundException e) {
78 Logger.getLogger(Slf4jLogFactory.class.getName()).log(
79 Level.WARNING,
80 "Failed bootstrap the SLF4J logger: " + e.getMessage(), e);
81 throw new RuntimeException(e);
82 }
83 catch (final NoSuchMethodException e) {
84 Logger.getLogger(Slf4jLogFactory.class.getName()).log(
85 Level.WARNING,
86 "Failed bootstrap the SLF4J logger: " + e.getMessage(), e);
87 throw new RuntimeException(e);
88 }
89 }
90
91
92
93
94
95
96
97
98
99 @Override
100 protected Log doGetLog(final Class<?> clazz) {
101 Log log = null;
102 try {
103 final Object logger = myLogFactoryMethod.invoke(null, clazz);
104 if (myLocationAwareLoggerClass.isInstance(logger)) {
105 log = new Slf4jLog(myLogMethod, logger);
106 }
107 }
108 catch (final IllegalAccessException e) {
109
110 }
111 catch (final InvocationTargetException e) {
112
113 }
114 catch (final RuntimeException e) {
115
116 }
117
118
119 if (log == null) {
120 Logger.getLogger(Slf4jLogFactory.class.getName()).warning(
121 "Falling back to the JUL logger.");
122 log = new JulLog(clazz);
123 }
124
125 return log;
126 }
127 }