|
36 | 36 | */
|
37 | 37 | final class LogAdapter {
|
38 | 38 |
|
39 |
| - private static LogApi logApi = LogApi.JUL; |
| 39 | + private static final String LOG4J_SPI = "org.apache.logging.log4j.spi.ExtendedLogger"; |
| 40 | + |
| 41 | + private static final String LOG4J_SLF4J_PROVIDER = "org.apache.logging.slf4j.SLF4JProvider"; |
| 42 | + |
| 43 | + private static final String SLF4J_SPI = "org.slf4j.spi.LocationAwareLogger"; |
| 44 | + |
| 45 | + private static final String SLF4J_API = "org.slf4j.Logger"; |
| 46 | + |
| 47 | + |
| 48 | + private static final LogApi logApi; |
40 | 49 |
|
41 | 50 | static {
|
42 |
| - ClassLoader cl = LogAdapter.class.getClassLoader(); |
43 |
| - try { |
44 |
| - // Try Log4j 2.x API |
45 |
| - Class.forName("org.apache.logging.log4j.spi.ExtendedLogger", false, cl); |
46 |
| - logApi = LogApi.LOG4J; |
47 |
| - } |
48 |
| - catch (ClassNotFoundException ex1) { |
49 |
| - try { |
50 |
| - // Try SLF4J 1.7 SPI |
51 |
| - Class.forName("org.slf4j.spi.LocationAwareLogger", false, cl); |
| 51 | + if (isPresent(LOG4J_SPI)) { |
| 52 | + if (isPresent(LOG4J_SLF4J_PROVIDER) && isPresent(SLF4J_SPI)) { |
| 53 | + // log4j-to-slf4j bridge -> we'll rather go with the SLF4J SPI; |
| 54 | + // however, we still prefer Log4j over the plain SLF4J API since |
| 55 | + // the latter does not have location awareness support. |
52 | 56 | logApi = LogApi.SLF4J_LAL;
|
53 | 57 | }
|
54 |
| - catch (ClassNotFoundException ex2) { |
55 |
| - try { |
56 |
| - // Try SLF4J 1.7 API |
57 |
| - Class.forName("org.slf4j.Logger", false, cl); |
58 |
| - logApi = LogApi.SLF4J; |
59 |
| - } |
60 |
| - catch (ClassNotFoundException ex3) { |
61 |
| - // Keep java.util.logging as default |
62 |
| - } |
| 58 | + else { |
| 59 | + // Use Log4j 2.x directly, including location awareness support |
| 60 | + logApi = LogApi.LOG4J; |
63 | 61 | }
|
64 | 62 | }
|
| 63 | + else if (isPresent(SLF4J_SPI)) { |
| 64 | + // Full SLF4J SPI including location awareness support |
| 65 | + logApi = LogApi.SLF4J_LAL; |
| 66 | + } |
| 67 | + else if (isPresent(SLF4J_API)) { |
| 68 | + // Minimal SLF4J API without location awareness support |
| 69 | + logApi = LogApi.SLF4J; |
| 70 | + } |
| 71 | + else { |
| 72 | + // java.util.logging as default |
| 73 | + logApi = LogApi.JUL; |
| 74 | + } |
65 | 75 | }
|
66 | 76 |
|
67 | 77 |
|
@@ -92,6 +102,16 @@ public static Log createLog(String name) {
|
92 | 102 | }
|
93 | 103 | }
|
94 | 104 |
|
| 105 | + private static boolean isPresent(String className) { |
| 106 | + try { |
| 107 | + Class.forName(className, false, LogAdapter.class.getClassLoader()); |
| 108 | + return true; |
| 109 | + } |
| 110 | + catch (ClassNotFoundException ex) { |
| 111 | + return false; |
| 112 | + } |
| 113 | + } |
| 114 | + |
95 | 115 |
|
96 | 116 | private enum LogApi {LOG4J, SLF4J_LAL, SLF4J, JUL}
|
97 | 117 |
|
|
0 commit comments