1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.logging;
17
18 import java.lang.reflect.Constructor;
19 import java.util.concurrent.locks.ReentrantLock;
20
21
22
23
24
25 public final class LogFactory {
26
27
28
29
30 public static final String MARKER = "MYBATIS";
31
32 private static final ReentrantLock lock = new ReentrantLock();
33 private static Constructor<? extends Log> logConstructor;
34
35 static {
36 tryImplementation(LogFactory::useSlf4jLogging);
37 tryImplementation(LogFactory::useCommonsLogging);
38 tryImplementation(LogFactory::useLog4J2Logging);
39 tryImplementation(LogFactory::useLog4JLogging);
40 tryImplementation(LogFactory::useJdkLogging);
41 tryImplementation(LogFactory::useNoLogging);
42 }
43
44 private LogFactory() {
45
46 }
47
48 public static Log getLog(Class<?> clazz) {
49 return getLog(clazz.getName());
50 }
51
52 public static Log getLog(String logger) {
53 try {
54 return logConstructor.newInstance(logger);
55 } catch (Throwable t) {
56 throw new LogException("Error creating logger for logger " + logger + ". Cause: " + t, t);
57 }
58 }
59
60 public static void useCustomLogging(Class<? extends Log> clazz) {
61 setImplementation(clazz);
62 }
63
64 public static void useSlf4jLogging() {
65 setImplementation(org.apache.ibatis.logging.slf4j.Slf4jImpl.class);
66 }
67
68 public static void useCommonsLogging() {
69 setImplementation(org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl.class);
70 }
71
72
73
74
75 @Deprecated
76 public static void useLog4JLogging() {
77 setImplementation(org.apache.ibatis.logging.log4j.Log4jImpl.class);
78 }
79
80 public static void useLog4J2Logging() {
81 setImplementation(org.apache.ibatis.logging.log4j2.Log4j2Impl.class);
82 }
83
84 public static void useJdkLogging() {
85 setImplementation(org.apache.ibatis.logging.jdk14.Jdk14LoggingImpl.class);
86 }
87
88 public static void useStdOutLogging() {
89 setImplementation(org.apache.ibatis.logging.stdout.StdOutImpl.class);
90 }
91
92 public static void useNoLogging() {
93 setImplementation(org.apache.ibatis.logging.nologging.NoLoggingImpl.class);
94 }
95
96 private static void tryImplementation(Runnable runnable) {
97 if (logConstructor == null) {
98 try {
99 runnable.run();
100 } catch (Throwable t) {
101
102 }
103 }
104 }
105
106 private static void setImplementation(Class<? extends Log> implClass) {
107 lock.lock();
108 try {
109 Constructor<? extends Log> candidate = implClass.getConstructor(String.class);
110 Log log = candidate.newInstance(LogFactory.class.getName());
111 if (log.isDebugEnabled()) {
112 log.debug("Logging initialized using '" + implClass + "' adapter.");
113 }
114 logConstructor = candidate;
115 } catch (Throwable t) {
116 throw new LogException("Error setting Log implementation. Cause: " + t, t);
117 } finally {
118 lock.unlock();
119 }
120 }
121
122 }