/
LogManager.java
2731 lines (2533 loc) · 114 KB
/
LogManager.java
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util.logging;
import java.io.*;
import java.util.*;
import java.security.*;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.concurrent.ConcurrentHashMap;
import java.nio.file.Paths;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jdk.internal.access.JavaAWTAccess;
import jdk.internal.access.SharedSecrets;
import sun.util.logging.internal.LoggingProviderImpl;
import static jdk.internal.logger.DefaultLoggerFinder.isSystem;
/**
* There is a single global LogManager object that is used to
* maintain a set of shared state about Loggers and log services.
* <p>
* This LogManager object:
* <ul>
* <li> Manages a hierarchical namespace of Logger objects. All
* named Loggers are stored in this namespace.
* <li> Manages a set of logging control properties. These are
* simple key-value pairs that can be used by Handlers and
* other logging objects to configure themselves.
* </ul>
* <p>
* The global LogManager object can be retrieved using LogManager.getLogManager().
* The LogManager object is created during class initialization and
* cannot subsequently be changed.
* <p>
* At startup the LogManager class is located using the
* java.util.logging.manager system property.
*
* <h2>LogManager Configuration</h2>
*
* A LogManager initializes the logging configuration via
* the {@link #readConfiguration()} method during LogManager initialization.
* By default, LogManager default configuration is used.
* The logging configuration read by LogManager must be in the
* {@linkplain Properties properties file} format.
* <p>
* The LogManager defines two optional system properties that allow control over
* the initial configuration, as specified in the {@link #readConfiguration()}
* method:
* <ul>
* <li>{@systemProperty java.util.logging.config.class}
* <li>{@systemProperty java.util.logging.config.file}
* </ul>
* <p>
* These two system properties may be specified on the command line to the "java"
* command, or as system property definitions passed to JNI_CreateJavaVM.
* <p>
* The {@linkplain Properties properties} for loggers and Handlers will have
* names starting with the dot-separated name for the handler or logger.<br>
* The global logging properties may include:
* <ul>
* <li>A property "handlers". This defines a whitespace or comma separated
* list of class names for handler classes to load and register as
* handlers on the root Logger (the Logger named ""). Each class
* name must be for a Handler class which has a default constructor.
* Note that these Handlers may be created lazily, when they are
* first used.
*
* <li>A property "<logger>.handlers". This defines a whitespace or
* comma separated list of class names for handlers classes to
* load and register as handlers to the specified logger. Each class
* name must be for a Handler class which has a default constructor.
* Note that these Handlers may be created lazily, when they are
* first used.
*
* <li>A property "<logger>.handlers.ensureCloseOnReset". This defines a
* a boolean value. If "<logger>.handlers" is not defined or is empty,
* this property is ignored. Otherwise it defaults to {@code true}. When the
* value is {@code true}, the handlers associated with the logger are guaranteed
* to be closed on {@linkplain #reset} and shutdown. This can be turned off
* by explicitly setting "<logger>.handlers.ensureCloseOnReset=false" in
* the configuration. Note that turning this property off causes the risk of
* introducing a resource leak, as the logger may get garbage collected before
* {@code reset()} is called, thus preventing its handlers from being closed
* on {@code reset()}. In that case it is the responsibility of the application
* to ensure that the handlers are closed before the logger is garbage
* collected.
*
* <li>A property "<logger>.useParentHandlers". This defines a boolean
* value. By default every logger calls its parent in addition to
* handling the logging message itself, this often result in messages
* being handled by the root logger as well. When setting this property
* to false a Handler needs to be configured for this logger otherwise
* no logging messages are delivered.
*
* <li>A property "config". This property is intended to allow
* arbitrary configuration code to be run. The property defines a
* whitespace or comma separated list of class names. A new instance will be
* created for each named class. The default constructor of each class
* may execute arbitrary code to update the logging configuration, such as
* setting logger levels, adding handlers, adding filters, etc.
* </ul>
* <p>
* Note that all classes loaded during LogManager configuration are
* first searched on the system class path before any user class path.
* That includes the LogManager class, any config classes, and any
* handler classes.
* <p>
* Loggers are organized into a naming hierarchy based on their
* dot separated names. Thus "a.b.c" is a child of "a.b", but
* "a.b1" and a.b2" are peers.
* <p>
* All properties whose names end with ".level" are assumed to define
* log levels for Loggers. Thus "foo.level" defines a log level for
* the logger called "foo" and (recursively) for any of its children
* in the naming hierarchy. Log Levels are applied in the order they
* are defined in the properties file. Thus level settings for child
* nodes in the tree should come after settings for their parents.
* The property name ".level" can be used to set the level for the
* root of the tree.
* <p>
* All methods on the LogManager object are multi-thread safe.
*
* @since 1.4
*/
public class LogManager {
// The global LogManager object
private static final LogManager manager;
// 'props' is assigned within a lock but accessed without it.
// Declaring it volatile makes sure that another thread will not
// be able to see a partially constructed 'props' object.
// (seeing a partially constructed 'props' object can result in
// NPE being thrown in Hashtable.get(), because it leaves the door
// open for props.getProperties() to be called before the construcor
// of Hashtable is actually completed).
private volatile Properties props = new Properties();
private static final Level defaultLevel = Level.INFO;
// LoggerContext for system loggers and user loggers
private final LoggerContext systemContext = new SystemLoggerContext();
private final LoggerContext userContext = new LoggerContext();
// non final field - make it volatile to make sure that other threads
// will see the new value once ensureLogManagerInitialized() has finished
// executing.
private volatile Logger rootLogger;
// Have we done the primordial reading of the configuration file?
// (Must be done after a suitable amount of java.lang.System
// initialization has been done)
private volatile boolean readPrimordialConfiguration;
// Have we initialized global (root) handlers yet?
// This gets set to STATE_UNINITIALIZED in readConfiguration
private static final int
STATE_INITIALIZED = 0, // initial state
STATE_INITIALIZING = 1,
STATE_READING_CONFIG = 2,
STATE_UNINITIALIZED = 3,
STATE_SHUTDOWN = 4; // terminal state
private volatile int globalHandlersState; // = STATE_INITIALIZED;
// A concurrency lock for reset(), readConfiguration() and Cleaner.
private final ReentrantLock configurationLock = new ReentrantLock();
// This list contains the loggers for which some handlers have been
// explicitly configured in the configuration file.
// It prevents these loggers from being arbitrarily garbage collected.
private static final class CloseOnReset {
private final Logger logger;
private CloseOnReset(Logger ref) {
this.logger = Objects.requireNonNull(ref);
}
@Override
public boolean equals(Object other) {
return (other instanceof CloseOnReset) && ((CloseOnReset)other).logger == logger;
}
@Override
public int hashCode() {
return System.identityHashCode(logger);
}
public Logger get() {
return logger;
}
public static CloseOnReset create(Logger logger) {
return new CloseOnReset(logger);
}
}
private final CopyOnWriteArrayList<CloseOnReset> closeOnResetLoggers =
new CopyOnWriteArrayList<>();
private final Map<Object, Runnable> listeners =
Collections.synchronizedMap(new IdentityHashMap<>());
static {
manager = AccessController.doPrivileged(new PrivilegedAction<LogManager>() {
@Override
public LogManager run() {
LogManager mgr = null;
String cname = null;
try {
cname = System.getProperty("java.util.logging.manager");
if (cname != null) {
try {
@SuppressWarnings("deprecation")
Object tmp = ClassLoader.getSystemClassLoader()
.loadClass(cname).newInstance();
mgr = (LogManager) tmp;
} catch (ClassNotFoundException ex) {
@SuppressWarnings("deprecation")
Object tmp = Thread.currentThread()
.getContextClassLoader().loadClass(cname).newInstance();
mgr = (LogManager) tmp;
}
}
} catch (Exception ex) {
System.err.println("Could not load Logmanager \"" + cname + "\"");
ex.printStackTrace();
}
if (mgr == null) {
mgr = new LogManager();
}
return mgr;
}
});
}
// This private class is used as a shutdown hook.
// It does a "reset" to close all open handlers.
private class Cleaner extends Thread {
private Cleaner() {
super(null, null, "Logging-Cleaner", 0, false);
/* Set context class loader to null in order to avoid
* keeping a strong reference to an application classloader.
*/
this.setContextClassLoader(null);
}
@Override
public void run() {
// This is to ensure the LogManager.<clinit> is completed
// before synchronized block. Otherwise deadlocks are possible.
LogManager mgr = manager;
// set globalHandlersState to STATE_SHUTDOWN atomically so that
// no attempts are made to (re)initialize the handlers or (re)read
// the configuration again. This is terminal state.
configurationLock.lock();
globalHandlersState = STATE_SHUTDOWN;
configurationLock.unlock();
// Do a reset to close all active handlers.
reset();
}
}
/**
* Protected constructor. This is protected so that container applications
* (such as J2EE containers) can subclass the object. It is non-public as
* it is intended that there only be one LogManager object, whose value is
* retrieved by calling LogManager.getLogManager.
*/
protected LogManager() {
this(checkSubclassPermissions());
}
private LogManager(Void checked) {
// Add a shutdown hook to close the global handlers.
try {
Runtime.getRuntime().addShutdownHook(new Cleaner());
} catch (IllegalStateException e) {
// If the VM is already shutting down,
// We do not need to register shutdownHook.
}
}
private static Void checkSubclassPermissions() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// These permission will be checked in the LogManager constructor,
// in order to register the Cleaner() thread as a shutdown hook.
// Check them here to avoid the penalty of constructing the object
// etc...
sm.checkPermission(new RuntimePermission("shutdownHooks"));
sm.checkPermission(new RuntimePermission("setContextClassLoader"));
}
return null;
}
/**
* Lazy initialization: if this instance of manager is the global
* manager then this method will read the initial configuration and
* add the root logger and global logger by calling addLogger().
*
* Note that it is subtly different from what we do in LoggerContext.
* In LoggerContext we're patching up the logger context tree in order to add
* the root and global logger *to the context tree*.
*
* For this to work, addLogger() must have already have been called
* once on the LogManager instance for the default logger being
* added.
*
* This is why ensureLogManagerInitialized() needs to be called before
* any logger is added to any logger context.
*
*/
private boolean initializedCalled = false;
private volatile boolean initializationDone = false;
final void ensureLogManagerInitialized() {
final LogManager owner = this;
if (initializationDone || owner != manager) {
// we don't want to do this twice, and we don't want to do
// this on private manager instances.
return;
}
// Maybe another thread has called ensureLogManagerInitialized()
// before us and is still executing it. If so we will block until
// the log manager has finished initialized, then acquire the monitor,
// notice that initializationDone is now true and return.
// Otherwise - we have come here first! We will acquire the monitor,
// see that initializationDone is still false, and perform the
// initialization.
//
configurationLock.lock();
try {
// If initializedCalled is true it means that we're already in
// the process of initializing the LogManager in this thread.
// There has been a recursive call to ensureLogManagerInitialized().
final boolean isRecursiveInitialization = (initializedCalled == true);
assert initializedCalled || !initializationDone
: "Initialization can't be done if initialized has not been called!";
if (isRecursiveInitialization || initializationDone) {
// If isRecursiveInitialization is true it means that we're
// already in the process of initializing the LogManager in
// this thread. There has been a recursive call to
// ensureLogManagerInitialized(). We should not proceed as
// it would lead to infinite recursion.
//
// If initializationDone is true then it means the manager
// has finished initializing; just return: we're done.
return;
}
// Calling addLogger below will in turn call requiresDefaultLogger()
// which will call ensureLogManagerInitialized().
// We use initializedCalled to break the recursion.
initializedCalled = true;
try {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
assert rootLogger == null;
assert initializedCalled && !initializationDone;
// create root logger before reading primordial
// configuration - to ensure that it will be added
// before the global logger, and not after.
final Logger root = owner.rootLogger = owner.new RootLogger();
// Read configuration.
owner.readPrimordialConfiguration();
// Create and retain Logger for the root of the namespace.
owner.addLogger(root);
// Initialize level if not yet initialized
if (!root.isLevelInitialized()) {
root.setLevel(defaultLevel);
}
// Adding the global Logger.
// Do not call Logger.getGlobal() here as this might trigger
// subtle inter-dependency issues.
@SuppressWarnings("deprecation")
final Logger global = Logger.global;
// Make sure the global logger will be registered in the
// global manager
owner.addLogger(global);
return null;
}
});
} finally {
initializationDone = true;
}
} finally {
configurationLock.unlock();
}
}
/**
* Returns the global LogManager object.
* @return the global LogManager object
*/
public static LogManager getLogManager() {
if (manager != null) {
manager.ensureLogManagerInitialized();
}
return manager;
}
private void readPrimordialConfiguration() { // must be called while holding configurationLock
if (!readPrimordialConfiguration) {
// If System.in/out/err are null, it's a good
// indication that we're still in the
// bootstrapping phase
if (System.out == null) {
return;
}
readPrimordialConfiguration = true;
try {
readConfiguration();
// Platform loggers begin to delegate to java.util.logging.Logger
jdk.internal.logger.BootstrapLogger.redirectTemporaryLoggers();
} catch (Exception ex) {
assert false : "Exception raised while reading logging configuration: " + ex;
}
}
}
// LoggerContext maps from AppContext
private WeakHashMap<Object, LoggerContext> contextsMap = null;
// Returns the LoggerContext for the user code (i.e. application or AppContext).
// Loggers are isolated from each AppContext.
private LoggerContext getUserContext() {
LoggerContext context = null;
SecurityManager sm = System.getSecurityManager();
JavaAWTAccess javaAwtAccess = SharedSecrets.getJavaAWTAccess();
if (sm != null && javaAwtAccess != null) {
// for each applet, it has its own LoggerContext isolated from others
final Object ecx = javaAwtAccess.getAppletContext();
if (ecx != null) {
synchronized (javaAwtAccess) {
// find the AppContext of the applet code
// will be null if we are in the main app context.
if (contextsMap == null) {
contextsMap = new WeakHashMap<>();
}
context = contextsMap.get(ecx);
if (context == null) {
// Create a new LoggerContext for the applet.
context = new LoggerContext();
contextsMap.put(ecx, context);
}
}
}
}
// for standalone app, return userContext
return context != null ? context : userContext;
}
// The system context.
final LoggerContext getSystemContext() {
return systemContext;
}
private List<LoggerContext> contexts() {
List<LoggerContext> cxs = new ArrayList<>();
cxs.add(getSystemContext());
cxs.add(getUserContext());
return cxs;
}
// Find or create a specified logger instance. If a logger has
// already been created with the given name it is returned.
// Otherwise a new logger instance is created and registered
// in the LogManager global namespace.
// This method will always return a non-null Logger object.
// Synchronization is not required here. All synchronization for
// adding a new Logger object is handled by addLogger().
//
// This method must delegate to the LogManager implementation to
// add a new Logger or return the one that has been added previously
// as a LogManager subclass may override the addLogger, getLogger,
// readConfiguration, and other methods.
Logger demandLogger(String name, String resourceBundleName, Class<?> caller) {
final Module module = caller == null ? null : caller.getModule();
return demandLogger(name, resourceBundleName, module);
}
Logger demandLogger(String name, String resourceBundleName, Module module) {
Logger result = getLogger(name);
if (result == null) {
// only allocate the new logger once
Logger newLogger = new Logger(name, resourceBundleName,
module, this, false);
do {
if (addLogger(newLogger)) {
// We successfully added the new Logger that we
// created above so return it without refetching.
return newLogger;
}
// We didn't add the new Logger that we created above
// because another thread added a Logger with the same
// name after our null check above and before our call
// to addLogger(). We have to refetch the Logger because
// addLogger() returns a boolean instead of the Logger
// reference itself. However, if the thread that created
// the other Logger is not holding a strong reference to
// the other Logger, then it is possible for the other
// Logger to be GC'ed after we saw it in addLogger() and
// before we can refetch it. If it has been GC'ed then
// we'll just loop around and try again.
result = getLogger(name);
} while (result == null);
}
return result;
}
Logger demandSystemLogger(String name, String resourceBundleName, Class<?> caller) {
final Module module = caller == null ? null : caller.getModule();
return demandSystemLogger(name, resourceBundleName, module);
}
Logger demandSystemLogger(String name, String resourceBundleName, Module module) {
// Add a system logger in the system context's namespace
final Logger sysLogger = getSystemContext()
.demandLogger(name, resourceBundleName, module);
// Add the system logger to the LogManager's namespace if not exist
// so that there is only one single logger of the given name.
// System loggers are visible to applications unless a logger of
// the same name has been added.
Logger logger;
do {
// First attempt to call addLogger instead of getLogger
// This would avoid potential bug in custom LogManager.getLogger
// implementation that adds a logger if does not exist
if (addLogger(sysLogger)) {
// successfully added the new system logger
logger = sysLogger;
} else {
logger = getLogger(name);
}
} while (logger == null);
// LogManager will set the sysLogger's handlers via LogManager.addLogger method.
if (logger != sysLogger) {
// if logger already exists we merge the two logger configurations.
final Logger l = logger;
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
l.mergeWithSystemLogger(sysLogger);
return null;
}
});
}
return sysLogger;
}
// LoggerContext maintains the logger namespace per context.
// The default LogManager implementation has one system context and user
// context. The system context is used to maintain the namespace for
// all system loggers and is queried by the system code. If a system logger
// doesn't exist in the user context, it'll also be added to the user context.
// The user context is queried by the user code and all other loggers are
// added in the user context.
class LoggerContext {
// Table of named Loggers that maps names to Loggers.
private final ConcurrentHashMap<String,LoggerWeakRef> namedLoggers =
new ConcurrentHashMap<>();
// Tree of named Loggers
private final LogNode root;
private LoggerContext() {
this.root = new LogNode(null, this);
}
// Tells whether default loggers are required in this context.
// If true, the default loggers will be lazily added.
final boolean requiresDefaultLoggers() {
final boolean requiresDefaultLoggers = (getOwner() == manager);
if (requiresDefaultLoggers) {
getOwner().ensureLogManagerInitialized();
}
return requiresDefaultLoggers;
}
// This context's LogManager.
final LogManager getOwner() {
return LogManager.this;
}
// This context owner's root logger, which if not null, and if
// the context requires default loggers, will be added to the context
// logger's tree.
final Logger getRootLogger() {
return getOwner().rootLogger;
}
// The global logger, which if not null, and if
// the context requires default loggers, will be added to the context
// logger's tree.
final Logger getGlobalLogger() {
@SuppressWarnings("deprecation") // avoids initialization cycles.
final Logger global = Logger.global;
return global;
}
Logger demandLogger(String name, String resourceBundleName, Module module) {
// a LogManager subclass may have its own implementation to add and
// get a Logger. So delegate to the LogManager to do the work.
final LogManager owner = getOwner();
return owner.demandLogger(name, resourceBundleName, module);
}
// Due to subtle deadlock issues getUserContext() no longer
// calls addLocalLogger(rootLogger);
// Therefore - we need to add the default loggers later on.
// Checks that the context is properly initialized
// This is necessary before calling e.g. find(name)
// or getLoggerNames()
//
private void ensureInitialized() {
if (requiresDefaultLoggers()) {
// Ensure that the root and global loggers are set.
ensureDefaultLogger(getRootLogger());
ensureDefaultLogger(getGlobalLogger());
}
}
Logger findLogger(String name) {
// Attempt to find logger without locking.
LoggerWeakRef ref = namedLoggers.get(name);
Logger logger = ref == null ? null : ref.get();
// if logger is not null, then we can return it right away.
// if name is "" or "global" and logger is null
// we need to fall through and check that this context is
// initialized.
// if ref is not null and logger is null we also need to
// fall through.
if (logger != null || (ref == null && !name.isEmpty()
&& !name.equals(Logger.GLOBAL_LOGGER_NAME))) {
return logger;
}
// We either found a stale reference, or we were looking for
// "" or "global" and didn't find them.
// Make sure context is initialized (has the default loggers),
// and look up again, cleaning the stale reference if it hasn't
// been cleaned up in between. All this needs to be done inside
// a synchronized block.
synchronized(this) {
// ensure that this context is properly initialized before
// looking for loggers.
ensureInitialized();
ref = namedLoggers.get(name);
if (ref == null) {
return null;
}
logger = ref.get();
if (logger == null) {
// The namedLoggers map holds stale weak reference
// to a logger which has been GC-ed.
ref.dispose();
}
return logger;
}
}
// This method is called before adding a logger to the
// context.
// 'logger' is the context that will be added.
// This method will ensure that the defaults loggers are added
// before adding 'logger'.
//
private void ensureAllDefaultLoggers(Logger logger) {
if (requiresDefaultLoggers()) {
final String name = logger.getName();
if (!name.isEmpty()) {
ensureDefaultLogger(getRootLogger());
if (!Logger.GLOBAL_LOGGER_NAME.equals(name)) {
ensureDefaultLogger(getGlobalLogger());
}
}
}
}
private void ensureDefaultLogger(Logger logger) {
// Used for lazy addition of root logger and global logger
// to a LoggerContext.
// This check is simple sanity: we do not want that this
// method be called for anything else than Logger.global
// or owner.rootLogger.
if (!requiresDefaultLoggers() || logger == null
|| logger != getGlobalLogger() && logger != LogManager.this.rootLogger ) {
// the case where we have a non null logger which is neither
// Logger.global nor manager.rootLogger indicates a serious
// issue - as ensureDefaultLogger should never be called
// with any other loggers than one of these two (or null - if
// e.g manager.rootLogger is not yet initialized)...
assert logger == null;
return;
}
// Adds the logger if it's not already there.
if (!namedLoggers.containsKey(logger.getName())) {
// It is important to prevent addLocalLogger to
// call ensureAllDefaultLoggers when we're in the process
// off adding one of those default loggers - as this would
// immediately cause a stack overflow.
// Therefore we must pass addDefaultLoggersIfNeeded=false,
// even if requiresDefaultLoggers is true.
addLocalLogger(logger, false);
}
}
boolean addLocalLogger(Logger logger) {
// no need to add default loggers if it's not required
return addLocalLogger(logger, requiresDefaultLoggers());
}
// Add a logger to this context. This method will only set its level
// and process parent loggers. It doesn't set its handlers.
synchronized boolean addLocalLogger(Logger logger, boolean addDefaultLoggersIfNeeded) {
// addDefaultLoggersIfNeeded serves to break recursion when adding
// default loggers. If we're adding one of the default loggers
// (we're being called from ensureDefaultLogger()) then
// addDefaultLoggersIfNeeded will be false: we don't want to
// call ensureAllDefaultLoggers again.
//
// Note: addDefaultLoggersIfNeeded can also be false when
// requiresDefaultLoggers is false - since calling
// ensureAllDefaultLoggers would have no effect in this case.
if (addDefaultLoggersIfNeeded) {
ensureAllDefaultLoggers(logger);
}
final String name = logger.getName();
if (name == null) {
throw new NullPointerException();
}
LoggerWeakRef ref = namedLoggers.get(name);
if (ref != null) {
if (ref.refersTo(null)) {
// It's possible that the Logger was GC'ed after a
// drainLoggerRefQueueBounded() call above so allow
// a new one to be registered.
ref.dispose();
} else {
// We already have a registered logger with the given name.
return false;
}
}
// We're adding a new logger.
// Note that we are creating a weak reference here.
final LogManager owner = getOwner();
logger.setLogManager(owner);
ref = owner.new LoggerWeakRef(logger);
// Apply any initial level defined for the new logger, unless
// the logger's level is already initialized
Level level = owner.getLevelProperty(name + ".level", null);
if (level != null && !logger.isLevelInitialized()) {
doSetLevel(logger, level);
}
// instantiation of the handler is done in the LogManager.addLogger
// implementation as a handler class may be only visible to LogManager
// subclass for the custom log manager case
processParentHandlers(logger, name, VisitedLoggers.NEVER);
// Find the new node and its parent.
LogNode node = getNode(name);
node.loggerRef = ref;
Logger parent = null;
LogNode nodep = node.parent;
while (nodep != null) {
LoggerWeakRef nodeRef = nodep.loggerRef;
if (nodeRef != null) {
parent = nodeRef.get();
if (parent != null) {
break;
}
}
nodep = nodep.parent;
}
if (parent != null) {
doSetParent(logger, parent);
}
// Walk over the children and tell them we are their new parent.
node.walkAndSetParent(logger);
// new LogNode is ready so tell the LoggerWeakRef about it
ref.setNode(node);
// Do not publish 'ref' in namedLoggers before the logger tree
// is fully updated - because the named logger will be visible as
// soon as it is published in namedLoggers (findLogger takes
// benefit of the ConcurrentHashMap implementation of namedLoggers
// to avoid synchronizing on retrieval when that is possible).
namedLoggers.put(name, ref);
return true;
}
void removeLoggerRef(String name, LoggerWeakRef ref) {
namedLoggers.remove(name, ref);
}
synchronized Enumeration<String> getLoggerNames() {
// ensure that this context is properly initialized before
// returning logger names.
ensureInitialized();
return Collections.enumeration(namedLoggers.keySet());
}
// If logger.getUseParentHandlers() returns 'true' and any of the logger's
// parents have levels or handlers defined, make sure they are instantiated.
private void processParentHandlers(final Logger logger, final String name,
Predicate<Logger> visited) {
final LogManager owner = getOwner();
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
if (logger != owner.rootLogger) {
boolean useParent = owner.getBooleanProperty(name + ".useParentHandlers", true);
if (!useParent) {
logger.setUseParentHandlers(false);
}
}
return null;
}
});
int ix = 1;
for (;;) {
int ix2 = name.indexOf('.', ix);
if (ix2 < 0) {
break;
}
String pname = name.substring(0, ix2);
if (owner.getProperty(pname + ".level") != null ||
owner.getProperty(pname + ".handlers") != null) {
// This pname has a level/handlers definition.
// Make sure it exists.
if (visited.test(demandLogger(pname, null, null))) {
break;
}
}
ix = ix2+1;
}
}
// Gets a node in our tree of logger nodes.
// If necessary, create it.
LogNode getNode(String name) {
if (name == null || name.isEmpty()) {
return root;
}
LogNode node = root;
while (name.length() > 0) {
int ix = name.indexOf('.');
String head;
if (ix > 0) {
head = name.substring(0, ix);
name = name.substring(ix + 1);
} else {
head = name;
name = "";
}
if (node.children == null) {
node.children = new HashMap<>();
}
LogNode child = node.children.get(head);
if (child == null) {
child = new LogNode(node, this);
node.children.put(head, child);
}
node = child;
}
return node;
}
}
final class SystemLoggerContext extends LoggerContext {
// Add a system logger in the system context's namespace as well as
// in the LogManager's namespace if not exist so that there is only
// one single logger of the given name. System loggers are visible
// to applications unless a logger of the same name has been added.
@Override
Logger demandLogger(String name, String resourceBundleName,
Module module) {
Logger result = findLogger(name);
if (result == null) {
// only allocate the new system logger once
Logger newLogger = new Logger(name, resourceBundleName,
module, getOwner(), true);
do {
if (addLocalLogger(newLogger)) {
// We successfully added the new Logger that we
// created above so return it without refetching.
result = newLogger;
} else {
// We didn't add the new Logger that we created above
// because another thread added a Logger with the same
// name after our null check above and before our call
// to addLogger(). We have to refetch the Logger because
// addLogger() returns a boolean instead of the Logger
// reference itself. However, if the thread that created
// the other Logger is not holding a strong reference to
// the other Logger, then it is possible for the other
// Logger to be GC'ed after we saw it in addLogger() and
// before we can refetch it. If it has been GC'ed then
// we'll just loop around and try again.
result = findLogger(name);
}
} while (result == null);
}
return result;
}
}
// Add new per logger handlers.
// We need to raise privilege here. All our decisions will
// be made based on the logging configuration, which can
// only be modified by trusted code.
private void loadLoggerHandlers(final Logger logger, final String name,
final String handlersPropertyName)
{
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
setLoggerHandlers(logger, name, handlersPropertyName,
createLoggerHandlers(name, handlersPropertyName));
return null;
}
});
}
private void setLoggerHandlers(final Logger logger, final String name,
final String handlersPropertyName,
List<Handler> handlers)
{
final boolean ensureCloseOnReset = ! handlers.isEmpty()
&& getBooleanProperty(handlersPropertyName + ".ensureCloseOnReset",true);
int count = 0;
for (Handler hdl : handlers) {
logger.addHandler(hdl);
if (++count == 1 && ensureCloseOnReset) {
// add this logger to the closeOnResetLoggers list.
closeOnResetLoggers.addIfAbsent(CloseOnReset.create(logger));
}
}
}
private List<Handler> createLoggerHandlers(final String name,
final String handlersPropertyName)
{
String names[] = parseClassNames(handlersPropertyName);
List<Handler> handlers = new ArrayList<>(names.length);
for (String type : names) {
try {
@SuppressWarnings("deprecation")
Object o = ClassLoader.getSystemClassLoader().loadClass(type).newInstance();