Spring日志源码之JCL

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.commons.logging;

/**
* A minimal incarnation of Apache Commons Logging's {@code LogFactory} API,
* providing just the common {@link Log} lookup methods. This is inspired
* by the JCL-over-SLF4J bridge and should be source as well as binary
* compatible with all common use of the Commons Logging API (in particular:
* with {@code LogFactory.getLog(Class/String)} field initializers).
*
* <p>This implementation does not support Commons Logging's original provider
* detection. It rather only checks for the presence of the Log4j 2.x API
* and the SLF4J 1.7 API in the Spring Framework classpath, falling back to
* {@code java.util.logging} if none of the two is available. In that sense,
* it works as a replacement for the Log4j 2 Commons Logging bridge as well as
* the JCL-over-SLF4J bridge, both of which become irrelevant for Spring-based
* setups as a consequence (with no need for manual excludes of the standard
* Commons Logging API jar anymore either). Furthermore, for simple setups
* without an external logging provider, Spring does not require any extra jar
* on the classpath anymore since this embedded log factory automatically
* delegates to {@code java.util.logging} in such a scenario.
*
* <p><b>Note that this Commons Logging variant is only meant to be used for
* infrastructure logging purposes in the core framework and in extensions.</b>
* It also serves as a common bridge for third-party libraries using the
* Commons Logging API, e.g. Apache HttpClient, and HtmlUnit, bringing
* them into the same consistent arrangement without any extra bridge jars.
*
* <p><b>For logging need in application code, prefer direct use of Log4j 2.x
* or SLF4J or {@code java.util.logging}.</b> Simply put Log4j 2.x or Logback
* (or another SLF4J provider) onto your classpath, without any extra bridges,
* and let the framework auto-adapt to your choice.
*
* @author Juergen Hoeller (for the {@code spring-jcl} variant)
* @since 5.0
*/
public abstract class LogFactory {

/**
* Convenience method to return a named logger.
* @param clazz containing Class from which a log name will be derived
*/
public static Log getLog(Class<?> clazz) {
return getLog(clazz.getName());
}

/**
* Convenience method to return a named logger.
* @param name logical name of the <code>Log</code> instance to be returned
*/
public static Log getLog(String name) {
return LogAdapter.createLog(name);
}


/**
* This method only exists for compatibility with unusual Commons Logging API
* usage like e.g. {@code LogFactory.getFactory().getInstance(Class/String)}.
* @see #getInstance(Class)
* @see #getInstance(String)
* @deprecated in favor of {@link #getLog(Class)}/{@link #getLog(String)}
*/
@Deprecated
public static LogFactory getFactory() {
return new LogFactory() {};
}

/**
* Convenience method to return a named logger.
* <p>This variant just dispatches straight to {@link #getLog(Class)}.
* @param clazz containing Class from which a log name will be derived
* @deprecated in favor of {@link #getLog(Class)}
*/
@Deprecated
public Log getInstance(Class<?> clazz) {
return getLog(clazz);
}

/**
* Convenience method to return a named logger.
* <p>This variant just dispatches straight to {@link #getLog(String)}.
* @param name logical name of the <code>Log</code> instance to be returned
* @deprecated in favor of {@link #getLog(String)}
*/
@Deprecated
public Log getInstance(String name) {
return getLog(name);
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.commons.logging;

import java.io.Serializable;
import java.util.logging.LogRecord;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.spi.ExtendedLogger;
import org.apache.logging.log4j.spi.LoggerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;

/**
* Spring's common JCL adapter behind {@link LogFactory} and {@link LogFactoryService}.
* Detects the presence of Log4j 2.x / SLF4J, falling back to {@code java.util.logging}.
*
* @author Juergen Hoeller
* @since 5.1
*/
final class LogAdapter {

private static final String LOG4J_SPI = "org.apache.logging.log4j.spi.ExtendedLogger";

private static final String LOG4J_SLF4J_PROVIDER = "org.apache.logging.slf4j.SLF4JProvider";

private static final String SLF4J_SPI = "org.slf4j.spi.LocationAwareLogger";

private static final String SLF4J_API = "org.slf4j.Logger";


private static final LogApi logApi;

/**
* @author cuishiying
* 静态代码块中的代码会在类加载JVM时运行,且只被执行一次
*/
static {
if (isPresent(LOG4J_SPI)) {
if (isPresent(LOG4J_SLF4J_PROVIDER) && isPresent(SLF4J_SPI)) {
// log4j-to-slf4j bridge -> we'll rather go with the SLF4J SPI;
// however, we still prefer Log4j over the plain SLF4J API since
// the latter does not have location awareness support.
logApi = LogApi.SLF4J_LAL;
}
else {
// Use Log4j 2.x directly, including location awareness support
logApi = LogApi.LOG4J;
}
}
else if (isPresent(SLF4J_SPI)) {
// Full SLF4J SPI including location awareness support
logApi = LogApi.SLF4J_LAL;
}
else if (isPresent(SLF4J_API)) {
// Minimal SLF4J API without location awareness support
logApi = LogApi.SLF4J;
}
else {
// java.util.logging as default
logApi = LogApi.JUL;
}
}


private LogAdapter() {
}


/**
* 工厂方法
* Create an actual {@link Log} instance for the selected API.
* @param name the logger name
*/
public static Log createLog(String name) {
switch (logApi) {
case LOG4J:
return Log4jAdapter.createLog(name);
case SLF4J_LAL:
return Slf4jAdapter.createLocationAwareLog(name);
case SLF4J:
return Slf4jAdapter.createLog(name);
default:
// Defensively use lazy-initializing adapter class here as well since the
// java.logging module is not present by default on JDK 9. We are requiring
// its presence if neither Log4j nor SLF4J is available; however, in the
// case of Log4j or SLF4J, we are trying to prevent early initialization
// of the JavaUtilLog adapter - e.g. by a JVM in debug mode - when eagerly
// trying to parse the bytecode for all the cases of this switch clause.
return JavaUtilAdapter.createLog(name);
}
}

private static boolean isPresent(String className) {
try {
Class.forName(className, false, LogAdapter.class.getClassLoader());
return true;
}
catch (ClassNotFoundException ex) {
return false;
}
}


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


private static class Log4jAdapter {

public static Log createLog(String name) {
return new Log4jLog(name);
}
}


private static class Slf4jAdapter {

public static Log createLocationAwareLog(String name) {
Logger logger = LoggerFactory.getLogger(name);
return (logger instanceof LocationAwareLogger ?
new Slf4jLocationAwareLog((LocationAwareLogger) logger) : new Slf4jLog<>(logger));
}

public static Log createLog(String name) {
return new Slf4jLog<>(LoggerFactory.getLogger(name));
}
}


private static class JavaUtilAdapter {

public static Log createLog(String name) {
return new JavaUtilLog(name);
}
}


/**
* 告诉编译器忽略指定的警告,不用在编译完成后出现警告信息
*/
@SuppressWarnings("serial")
private static class Log4jLog implements Log, Serializable {

private static final String FQCN = Log4jLog.class.getName();

private static final LoggerContext loggerContext =
LogManager.getContext(Log4jLog.class.getClassLoader(), false);

private final ExtendedLogger logger;

public Log4jLog(String name) {
LoggerContext context = loggerContext;
if (context == null) {
// Circular call in early-init scenario -> static field not initialized yet
context = LogManager.getContext(Log4jLog.class.getClassLoader(), false);
}
this.logger = context.getLogger(name);
}

@Override
public boolean isFatalEnabled() {
return this.logger.isEnabled(Level.FATAL);
}

@Override
public boolean isErrorEnabled() {
return this.logger.isEnabled(Level.ERROR);
}

@Override
public boolean isWarnEnabled() {
return this.logger.isEnabled(Level.WARN);
}

@Override
public boolean isInfoEnabled() {
return this.logger.isEnabled(Level.INFO);
}

@Override
public boolean isDebugEnabled() {
return this.logger.isEnabled(Level.DEBUG);
}

@Override
public boolean isTraceEnabled() {
return this.logger.isEnabled(Level.TRACE);
}

@Override
public void fatal(Object message) {
log(Level.FATAL, message, null);
}

@Override
public void fatal(Object message, Throwable exception) {
log(Level.FATAL, message, exception);
}

@Override
public void error(Object message) {
log(Level.ERROR, message, null);
}

@Override
public void error(Object message, Throwable exception) {
log(Level.ERROR, message, exception);
}

@Override
public void warn(Object message) {
log(Level.WARN, message, null);
}

@Override
public void warn(Object message, Throwable exception) {
log(Level.WARN, message, exception);
}

@Override
public void info(Object message) {
log(Level.INFO, message, null);
}

@Override
public void info(Object message, Throwable exception) {
log(Level.INFO, message, exception);
}

@Override
public void debug(Object message) {
log(Level.DEBUG, message, null);
}

@Override
public void debug(Object message, Throwable exception) {
log(Level.DEBUG, message, exception);
}

@Override
public void trace(Object message) {
log(Level.TRACE, message, null);
}

@Override
public void trace(Object message, Throwable exception) {
log(Level.TRACE, message, exception);
}

private void log(Level level, Object message, Throwable exception) {
if (message instanceof String) {
// Explicitly pass a String argument, avoiding Log4j's argument expansion
// for message objects in case of "{}" sequences (SPR-16226)
if (exception != null) {
this.logger.logIfEnabled(FQCN, level, null, (String) message, exception);
}
else {
this.logger.logIfEnabled(FQCN, level, null, (String) message);
}
}
else {
this.logger.logIfEnabled(FQCN, level, null, message, exception);
}
}
}


@SuppressWarnings("serial")
private static class Slf4jLog<T extends Logger> implements Log, Serializable {

protected final String name;

protected transient T logger;

public Slf4jLog(T logger) {
this.name = logger.getName();
this.logger = logger;
}

@Override
public boolean isFatalEnabled() {
return isErrorEnabled();
}

@Override
public boolean isErrorEnabled() {
return this.logger.isErrorEnabled();
}

@Override
public boolean isWarnEnabled() {
return this.logger.isWarnEnabled();
}

@Override
public boolean isInfoEnabled() {
return this.logger.isInfoEnabled();
}

@Override
public boolean isDebugEnabled() {
return this.logger.isDebugEnabled();
}

@Override
public boolean isTraceEnabled() {
return this.logger.isTraceEnabled();
}

@Override
public void fatal(Object message) {
error(message);
}

@Override
public void fatal(Object message, Throwable exception) {
error(message, exception);
}

@Override
public void error(Object message) {
if (message instanceof String || this.logger.isErrorEnabled()) {
this.logger.error(String.valueOf(message));
}
}

@Override
public void error(Object message, Throwable exception) {
if (message instanceof String || this.logger.isErrorEnabled()) {
this.logger.error(String.valueOf(message), exception);
}
}

@Override
public void warn(Object message) {
if (message instanceof String || this.logger.isWarnEnabled()) {
this.logger.warn(String.valueOf(message));
}
}

@Override
public void warn(Object message, Throwable exception) {
if (message instanceof String || this.logger.isWarnEnabled()) {
this.logger.warn(String.valueOf(message), exception);
}
}

@Override
public void info(Object message) {
if (message instanceof String || this.logger.isInfoEnabled()) {
this.logger.info(String.valueOf(message));
}
}

@Override
public void info(Object message, Throwable exception) {
if (message instanceof String || this.logger.isInfoEnabled()) {
this.logger.info(String.valueOf(message), exception);
}
}

@Override
public void debug(Object message) {
if (message instanceof String || this.logger.isDebugEnabled()) {
this.logger.debug(String.valueOf(message));
}
}

@Override
public void debug(Object message, Throwable exception) {
if (message instanceof String || this.logger.isDebugEnabled()) {
this.logger.debug(String.valueOf(message), exception);
}
}

@Override
public void trace(Object message) {
if (message instanceof String || this.logger.isTraceEnabled()) {
this.logger.trace(String.valueOf(message));
}
}

@Override
public void trace(Object message, Throwable exception) {
if (message instanceof String || this.logger.isTraceEnabled()) {
this.logger.trace(String.valueOf(message), exception);
}
}

protected Object readResolve() {
return Slf4jAdapter.createLog(this.name);
}
}


@SuppressWarnings("serial")
private static class Slf4jLocationAwareLog extends Slf4jLog<LocationAwareLogger> implements Serializable {

private static final String FQCN = Slf4jLocationAwareLog.class.getName();

public Slf4jLocationAwareLog(LocationAwareLogger logger) {
super(logger);
}

@Override
public void fatal(Object message) {
error(message);
}

@Override
public void fatal(Object message, Throwable exception) {
error(message, exception);
}

@Override
public void error(Object message) {
if (message instanceof String || this.logger.isErrorEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null);
}
}

@Override
public void error(Object message, Throwable exception) {
if (message instanceof String || this.logger.isErrorEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, exception);
}
}

@Override
public void warn(Object message) {
if (message instanceof String || this.logger.isWarnEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, null);
}
}

@Override
public void warn(Object message, Throwable exception) {
if (message instanceof String || this.logger.isWarnEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, exception);
}
}

@Override
public void info(Object message) {
if (message instanceof String || this.logger.isInfoEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, null);
}
}

@Override
public void info(Object message, Throwable exception) {
if (message instanceof String || this.logger.isInfoEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, exception);
}
}

@Override
public void debug(Object message) {
if (message instanceof String || this.logger.isDebugEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, null);
}
}

@Override
public void debug(Object message, Throwable exception) {
if (message instanceof String || this.logger.isDebugEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, exception);
}
}

@Override
public void trace(Object message) {
if (message instanceof String || this.logger.isTraceEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, null);
}
}

@Override
public void trace(Object message, Throwable exception) {
if (message instanceof String || this.logger.isTraceEnabled()) {
this.logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, exception);
}
}

@Override
protected Object readResolve() {
return Slf4jAdapter.createLocationAwareLog(this.name);
}
}


@SuppressWarnings("serial")
private static class JavaUtilLog implements Log, Serializable {

private String name;

private transient java.util.logging.Logger logger;

public JavaUtilLog(String name) {
this.name = name;
this.logger = java.util.logging.Logger.getLogger(name);
}

@Override
public boolean isFatalEnabled() {
return isErrorEnabled();
}

@Override
public boolean isErrorEnabled() {
return this.logger.isLoggable(java.util.logging.Level.SEVERE);
}

@Override
public boolean isWarnEnabled() {
return this.logger.isLoggable(java.util.logging.Level.WARNING);
}

@Override
public boolean isInfoEnabled() {
return this.logger.isLoggable(java.util.logging.Level.INFO);
}

@Override
public boolean isDebugEnabled() {
return this.logger.isLoggable(java.util.logging.Level.FINE);
}

@Override
public boolean isTraceEnabled() {
return this.logger.isLoggable(java.util.logging.Level.FINEST);
}

@Override
public void fatal(Object message) {
error(message);
}

@Override
public void fatal(Object message, Throwable exception) {
error(message, exception);
}

@Override
public void error(Object message) {
log(java.util.logging.Level.SEVERE, message, null);
}

@Override
public void error(Object message, Throwable exception) {
log(java.util.logging.Level.SEVERE, message, exception);
}

@Override
public void warn(Object message) {
log(java.util.logging.Level.WARNING, message, null);
}

@Override
public void warn(Object message, Throwable exception) {
log(java.util.logging.Level.WARNING, message, exception);
}

@Override
public void info(Object message) {
log(java.util.logging.Level.INFO, message, null);
}

@Override
public void info(Object message, Throwable exception) {
log(java.util.logging.Level.INFO, message, exception);
}

@Override
public void debug(Object message) {
log(java.util.logging.Level.FINE, message, null);
}

@Override
public void debug(Object message, Throwable exception) {
log(java.util.logging.Level.FINE, message, exception);
}

@Override
public void trace(Object message) {
log(java.util.logging.Level.FINEST, message, null);
}

@Override
public void trace(Object message, Throwable exception) {
log(java.util.logging.Level.FINEST, message, exception);
}

private void log(java.util.logging.Level level, Object message, Throwable exception) {
if (this.logger.isLoggable(level)) {
LogRecord rec;
if (message instanceof LogRecord) {
rec = (LogRecord) message;
}
else {
rec = new LocationResolvingLogRecord(level, String.valueOf(message));
rec.setLoggerName(this.name);
rec.setResourceBundleName(this.logger.getResourceBundleName());
rec.setResourceBundle(this.logger.getResourceBundle());
rec.setThrown(exception);
}
logger.log(rec);
}
}

protected Object readResolve() {
return new JavaUtilLog(this.name);
}
}


@SuppressWarnings("serial")
private static class LocationResolvingLogRecord extends LogRecord {

private static final String FQCN = JavaUtilLog.class.getName();

private volatile boolean resolved;

public LocationResolvingLogRecord(java.util.logging.Level level, String msg) {
super(level, msg);
}

@Override
public String getSourceClassName() {
if (!this.resolved) {
resolve();
}
return super.getSourceClassName();
}

@Override
public void setSourceClassName(String sourceClassName) {
super.setSourceClassName(sourceClassName);
this.resolved = true;
}

@Override
public String getSourceMethodName() {
if (!this.resolved) {
resolve();
}
return super.getSourceMethodName();
}

@Override
public void setSourceMethodName(String sourceMethodName) {
super.setSourceMethodName(sourceMethodName);
this.resolved = true;
}

private void resolve() {
StackTraceElement[] stack = new Throwable().getStackTrace();
String sourceClassName = null;
String sourceMethodName = null;
boolean found = false;
for (StackTraceElement element : stack) {
String className = element.getClassName();
if (FQCN.equals(className)) {
found = true;
}
else if (found) {
sourceClassName = className;
sourceMethodName = element.getMethodName();
break;
}
}
setSourceClassName(sourceClassName);
setSourceMethodName(sourceMethodName);
}

@SuppressWarnings("deprecation") // setMillis is deprecated in JDK 9
protected Object writeReplace() {
LogRecord serialized = new LogRecord(getLevel(), getMessage());
serialized.setLoggerName(getLoggerName());
serialized.setResourceBundle(getResourceBundle());
serialized.setResourceBundleName(getResourceBundleName());
serialized.setSourceClassName(getSourceClassName());
serialized.setSourceMethodName(getSourceMethodName());
serialized.setSequenceNumber(getSequenceNumber());
serialized.setParameters(getParameters());
serialized.setThreadID(getThreadID());
serialized.setMillis(getMillis());
serialized.setThrown(getThrown());
return serialized;
}
}

}

在其他项目中看到类似实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// EnvironmentAware 获取类加载器
ConfigurableEnvironment env = (ConfigurableEnvironment)environment;
ClassLoader classLoader = env.getClass().getClassLoader();

// 判断log4j2
public static boolean isLog4j2Usable(ClassLoader classloader) {

try {
return (classloader.loadClass("org.apache.logging.slf4j.Log4jLoggerFactory") != null);
} catch (ClassNotFoundException e) {
return false;
}
}


// 判断logback
public static boolean isLogbackUsable(ClassLoader classloader) {

try {
return classloader.loadClass("ch.qos.logback.classic.LoggerContext") != null;
} catch (ClassNotFoundException e) {
return false;
}
}

// 根据不同的log包做不同的初始化
private static LogEnhancer doInit(ClassLoader classLoader) {

LogEnhancer enhancer = null;
if(LogEnvUtils.isLog4j2Usable(classLoader)) {
enhancer = new DefaultLog4j2Enhancer(classLoader);
} else if(LogEnvUtils.isLogbackUsable(classLoader)) {
enhancer = new DefaultLogbackEnhancer(classLoader);
} else {
throw new IllegalStateException("No applicable logging system found");
}

return enhancer;
}

最后

本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】,您的支持是我写作的最大动力。