Skip to content

Commit 4b45030

Browse files
committed
Prefer SLF4J SPI over Log4J in case of log4j-to-slf4j bridge
Issue: SPR-17586
1 parent 73a96c5 commit 4b45030

File tree

1 file changed

+40
-20
lines changed

1 file changed

+40
-20
lines changed

spring-jcl/src/main/java/org/apache/commons/logging/LogAdapter.java

+40-20
Original file line numberDiff line numberDiff line change
@@ -36,32 +36,42 @@
3636
*/
3737
final class LogAdapter {
3838

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;
4049

4150
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.
5256
logApi = LogApi.SLF4J_LAL;
5357
}
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;
6361
}
6462
}
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+
}
6575
}
6676

6777

@@ -92,6 +102,16 @@ public static Log createLog(String name) {
92102
}
93103
}
94104

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+
95115

96116
private enum LogApi {LOG4J, SLF4J_LAL, SLF4J, JUL}
97117

0 commit comments

Comments
 (0)