1 /* 2 * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 27 package java.util.logging; 28 29 import java.io.*; 30 import java.util.*; 31 import java.security.*; 32 import java.lang.ref.ReferenceQueue; 33 import java.lang.ref.WeakReference; 34 import java.util.concurrent.ConcurrentHashMap; 35 import java.nio.file.Paths; 36 import java.util.concurrent.CopyOnWriteArrayList; 37 import java.util.concurrent.locks.ReentrantLock; 38 import java.util.function.BiFunction; 39 import java.util.function.Function; 40 import java.util.function.Predicate; 41 import java.util.stream.Collectors; 42 import java.util.stream.Stream; 43 import jdk.internal.misc.JavaAWTAccess; 44 import jdk.internal.misc.SharedSecrets; 45 import sun.util.logging.internal.LoggingProviderImpl; 46 47 /** 48 * There is a single global LogManager object that is used to 49 * maintain a set of shared state about Loggers and log services. 50 * <p> 51 * This LogManager object: 52 * <ul> 53 * <li> Manages a hierarchical namespace of Logger objects. All 54 * named Loggers are stored in this namespace. 55 * <li> Manages a set of logging control properties. These are 56 * simple key-value pairs that can be used by Handlers and 57 * other logging objects to configure themselves. 58 * </ul> 59 * <p> 60 * The global LogManager object can be retrieved using LogManager.getLogManager(). 61 * The LogManager object is created during class initialization and 62 * cannot subsequently be changed. 63 * <p> 64 * At startup the LogManager class is located using the 65 * java.util.logging.manager system property. 66 * 67 * <h3>LogManager Configuration</h3> 68 * 69 * A LogManager initializes the logging configuration via 70 * the {@link #readConfiguration()} method during LogManager initialization. 71 * By default, LogManager default configuration is used. 72 * The logging configuration read by LogManager must be in the 73 * {@linkplain Properties properties file} format. 74 * <p> 75 * The LogManager defines two optional system properties that allow control over 76 * the initial configuration, as specified in the {@link #readConfiguration()} 77 * method: 78 * <ul> 79 * <li>"java.util.logging.config.class" 80 * <li>"java.util.logging.config.file" 81 * </ul> 82 * <p> 83 * These two system properties may be specified on the command line to the "java" 84 * command, or as system property definitions passed to JNI_CreateJavaVM. 85 * <p> 86 * The {@linkplain Properties properties} for loggers and Handlers will have 87 * names starting with the dot-separated name for the handler or logger.<br> 88 * The global logging properties may include: 89 * <ul> 90 * <li>A property "handlers". This defines a whitespace or comma separated 91 * list of class names for handler classes to load and register as 92 * handlers on the root Logger (the Logger named ""). Each class 93 * name must be for a Handler class which has a default constructor. 94 * Note that these Handlers may be created lazily, when they are 95 * first used. 96 * 97 * <li>A property "<logger>.handlers". This defines a whitespace or 98 * comma separated list of class names for handlers classes to 99 * load and register as handlers to the specified logger. Each class 100 * name must be for a Handler class which has a default constructor. 101 * Note that these Handlers may be created lazily, when they are 102 * first used. 103 * 104 * <li>A property "<logger>.handlers.ensureCloseOnReset". This defines a 105 * a boolean value. If "<logger>.handlers" is not defined or is empty, 106 * this property is ignored. Otherwise it defaults to {@code true}. When the 107 * value is {@code true}, the handlers associated with the logger are guaranteed 108 * to be closed on {@linkplain #reset} and shutdown. This can be turned off 109 * by explicitly setting "<logger>.handlers.ensureCloseOnReset=false" in 110 * the configuration. Note that turning this property off causes the risk of 111 * introducing a resource leak, as the logger may get garbage collected before 112 * {@code reset()} is called, thus preventing its handlers from being closed 113 * on {@code reset()}. In that case it is the responsibility of the application 114 * to ensure that the handlers are closed before the logger is garbage 115 * collected. 116 * 117 * <li>A property "<logger>.useParentHandlers". This defines a boolean 118 * value. By default every logger calls its parent in addition to 119 * handling the logging message itself, this often result in messages 120 * being handled by the root logger as well. When setting this property 121 * to false a Handler needs to be configured for this logger otherwise 122 * no logging messages are delivered. 123 * 124 * <li>A property "config". This property is intended to allow 125 * arbitrary configuration code to be run. The property defines a 126 * whitespace or comma separated list of class names. A new instance will be 127 * created for each named class. The default constructor of each class 128 * may execute arbitrary code to update the logging configuration, such as 129 * setting logger levels, adding handlers, adding filters, etc. 130 * </ul> 131 * <p> 132 * Note that all classes loaded during LogManager configuration are 133 * first searched on the system class path before any user class path. 134 * That includes the LogManager class, any config classes, and any 135 * handler classes. 136 * <p> 137 * Loggers are organized into a naming hierarchy based on their 138 * dot separated names. Thus "a.b.c" is a child of "a.b", but 139 * "a.b1" and a.b2" are peers. 140 * <p> 141 * All properties whose names end with ".level" are assumed to define 142 * log levels for Loggers. Thus "foo.level" defines a log level for 143 * the logger called "foo" and (recursively) for any of its children 144 * in the naming hierarchy. Log Levels are applied in the order they 145 * are defined in the properties file. Thus level settings for child 146 * nodes in the tree should come after settings for their parents. 147 * The property name ".level" can be used to set the level for the 148 * root of the tree. 149 * <p> 150 * All methods on the LogManager object are multi-thread safe. 151 * 152 * @since 1.4 153 */ 154 155 public class LogManager { 156 // The global LogManager object 157 private static final LogManager manager; 158 159 // 'props' is assigned within a lock but accessed without it. 160 // Declaring it volatile makes sure that another thread will not 161 // be able to see a partially constructed 'props' object. 162 // (seeing a partially constructed 'props' object can result in 163 // NPE being thrown in Hashtable.get(), because it leaves the door 164 // open for props.getProperties() to be called before the construcor 165 // of Hashtable is actually completed). 166 private volatile Properties props = new Properties(); 167 private final static Level defaultLevel = Level.INFO; 168 169 // LoggerContext for system loggers and user loggers 170 private final LoggerContext systemContext = new SystemLoggerContext(); 171 private final LoggerContext userContext = new LoggerContext(); 172 // non final field - make it volatile to make sure that other threads 173 // will see the new value once ensureLogManagerInitialized() has finished 174 // executing. 175 private volatile Logger rootLogger; 176 // Have we done the primordial reading of the configuration file? 177 // (Must be done after a suitable amount of java.lang.System 178 // initialization has been done) 179 private volatile boolean readPrimordialConfiguration; 180 // Have we initialized global (root) handlers yet? 181 // This gets set to STATE_UNINITIALIZED in readConfiguration 182 private static final int 183 STATE_INITIALIZED = 0, // initial state 184 STATE_INITIALIZING = 1, 185 STATE_READING_CONFIG = 2, 186 STATE_UNINITIALIZED = 3, 187 STATE_SHUTDOWN = 4; // terminal state 188 private volatile int globalHandlersState; // = STATE_INITIALIZED; 189 // A concurrency lock for reset(), readConfiguration() and Cleaner. 190 private final ReentrantLock configurationLock = new ReentrantLock(); 191 192 // This list contains the loggers for which some handlers have been 193 // explicitly configured in the configuration file. 194 // It prevents these loggers from being arbitrarily garbage collected. 195 private static final class CloseOnReset { 196 private final Logger logger; 197 private CloseOnReset(Logger ref) { 198 this.logger = Objects.requireNonNull(ref); 199 } 200 @Override 201 public boolean equals(Object other) { 202 return (other instanceof CloseOnReset) && ((CloseOnReset)other).logger == logger; 203 } 204 @Override 205 public int hashCode() { 206 return System.identityHashCode(logger); 207 } 208 public Logger get() { 209 return logger; 210 } 211 public static CloseOnReset create(Logger logger) { 212 return new CloseOnReset(logger); 213 } 214 } 215 private final CopyOnWriteArrayList<CloseOnReset> closeOnResetLoggers = 216 new CopyOnWriteArrayList<>(); 217 218 219 private final Map<Object, Runnable> listeners = 220 Collections.synchronizedMap(new IdentityHashMap<>()); 221 222 static { 223 manager = AccessController.doPrivileged(new PrivilegedAction<LogManager>() { 224 @Override 225 public LogManager run() { 226 LogManager mgr = null; 227 String cname = null; 228 try { 229 cname = System.getProperty("java.util.logging.manager"); 230 if (cname != null) { 231 try { 232 @SuppressWarnings("deprecation") 233 Object tmp = ClassLoader.getSystemClassLoader() 234 .loadClass(cname).newInstance(); 235 mgr = (LogManager) tmp; 236 } catch (ClassNotFoundException ex) { 237 @SuppressWarnings("deprecation") 238 Object tmp = Thread.currentThread() 239 .getContextClassLoader().loadClass(cname).newInstance(); 240 mgr = (LogManager) tmp; 241 } 242 } 243 } catch (Exception ex) { 244 System.err.println("Could not load Logmanager \"" + cname + "\""); 245 ex.printStackTrace(); 246 } 247 if (mgr == null) { 248 mgr = new LogManager(); 249 } 250 return mgr; 251 252 } 253 }); 254 } 255 256 // This private class is used as a shutdown hook. 257 // It does a "reset" to close all open handlers. 258 private class Cleaner extends Thread { 259 260 private Cleaner() { 261 super(null, null, "Logging-Cleaner", 0, false); 262 /* Set context class loader to null in order to avoid 263 * keeping a strong reference to an application classloader. 264 */ 265 this.setContextClassLoader(null); 266 } 267 268 @Override 269 public void run() { 270 // This is to ensure the LogManager.<clinit> is completed 271 // before synchronized block. Otherwise deadlocks are possible. 272 LogManager mgr = manager; 273 274 // set globalHandlersState to STATE_SHUTDOWN atomically so that 275 // no attempts are made to (re)initialize the handlers or (re)read 276 // the configuration again. This is terminal state. 277 configurationLock.lock(); 278 globalHandlersState = STATE_SHUTDOWN; 279 configurationLock.unlock(); 280 281 // Do a reset to close all active handlers. 282 reset(); 283 } 284 } 285 286 287 /** 288 * Protected constructor. This is protected so that container applications 289 * (such as J2EE containers) can subclass the object. It is non-public as 290 * it is intended that there only be one LogManager object, whose value is 291 * retrieved by calling LogManager.getLogManager. 292 */ 293 protected LogManager() { 294 this(checkSubclassPermissions()); 295 } 296 297 private LogManager(Void checked) { 298 299 // Add a shutdown hook to close the global handlers. 300 try { 301 Runtime.getRuntime().addShutdownHook(new Cleaner()); 302 } catch (IllegalStateException e) { 303 // If the VM is already shutting down, 304 // We do not need to register shutdownHook. 305 } 306 } 307 308 private static Void checkSubclassPermissions() { 309 final SecurityManager sm = System.getSecurityManager(); 310 if (sm != null) { 311 // These permission will be checked in the LogManager constructor, 312 // in order to register the Cleaner() thread as a shutdown hook. 313 // Check them here to avoid the penalty of constructing the object 314 // etc... 315 sm.checkPermission(new RuntimePermission("shutdownHooks")); 316 sm.checkPermission(new RuntimePermission("setContextClassLoader")); 317 } 318 return null; 319 } 320 321 /** 322 * Lazy initialization: if this instance of manager is the global 323 * manager then this method will read the initial configuration and 324 * add the root logger and global logger by calling addLogger(). 325 * 326 * Note that it is subtly different from what we do in LoggerContext. 327 * In LoggerContext we're patching up the logger context tree in order to add 328 * the root and global logger *to the context tree*. 329 * 330 * For this to work, addLogger() must have already have been called 331 * once on the LogManager instance for the default logger being 332 * added. 333 * 334 * This is why ensureLogManagerInitialized() needs to be called before 335 * any logger is added to any logger context. 336 * 337 */ 338 private boolean initializedCalled = false; 339 private volatile boolean initializationDone = false; 340 final void ensureLogManagerInitialized() { 341 final LogManager owner = this; 342 if (initializationDone || owner != manager) { 343 // we don't want to do this twice, and we don't want to do 344 // this on private manager instances. 345 return; 346 } 347 348 // Maybe another thread has called ensureLogManagerInitialized() 349 // before us and is still executing it. If so we will block until 350 // the log manager has finished initialized, then acquire the monitor, 351 // notice that initializationDone is now true and return. 352 // Otherwise - we have come here first! We will acquire the monitor, 353 // see that initializationDone is still false, and perform the 354 // initialization. 355 // 356 configurationLock.lock(); 357 try { 358 // If initializedCalled is true it means that we're already in 359 // the process of initializing the LogManager in this thread. 360 // There has been a recursive call to ensureLogManagerInitialized(). 361 final boolean isRecursiveInitialization = (initializedCalled == true); 362 363 assert initializedCalled || !initializationDone 364 : "Initialization can't be done if initialized has not been called!"; 365 366 if (isRecursiveInitialization || initializationDone) { 367 // If isRecursiveInitialization is true it means that we're 368 // already in the process of initializing the LogManager in 369 // this thread. There has been a recursive call to 370 // ensureLogManagerInitialized(). We should not proceed as 371 // it would lead to infinite recursion. 372 // 373 // If initializationDone is true then it means the manager 374 // has finished initializing; just return: we're done. 375 return; 376 } 377 // Calling addLogger below will in turn call requiresDefaultLogger() 378 // which will call ensureLogManagerInitialized(). 379 // We use initializedCalled to break the recursion. 380 initializedCalled = true; 381 try { 382 AccessController.doPrivileged(new PrivilegedAction<Object>() { 383 @Override 384 public Object run() { 385 assert rootLogger == null; 386 assert initializedCalled && !initializationDone; 387 388 // Read configuration. 389 owner.readPrimordialConfiguration(); 390 391 // Create and retain Logger for the root of the namespace. 392 owner.rootLogger = owner.new RootLogger(); 393 owner.addLogger(owner.rootLogger); 394 if (!owner.rootLogger.isLevelInitialized()) { 395 owner.rootLogger.setLevel(defaultLevel); 396 } 397 398 // Adding the global Logger. 399 // Do not call Logger.getGlobal() here as this might trigger 400 // subtle inter-dependency issues. 401 @SuppressWarnings("deprecation") 402 final Logger global = Logger.global; 403 404 // Make sure the global logger will be registered in the 405 // global manager 406 owner.addLogger(global); 407 return null; 408 } 409 }); 410 } finally { 411 initializationDone = true; 412 } 413 } finally { 414 configurationLock.unlock(); 415 } 416 } 417 418 /** 419 * Returns the global LogManager object. 420 * @return the global LogManager object 421 */ 422 public static LogManager getLogManager() { 423 if (manager != null) { 424 manager.ensureLogManagerInitialized(); 425 } 426 return manager; 427 } 428 429 private void readPrimordialConfiguration() { // must be called while holding configurationLock 430 if (!readPrimordialConfiguration) { 431 // If System.in/out/err are null, it's a good 432 // indication that we're still in the 433 // bootstrapping phase 434 if (System.out == null) { 435 return; 436 } 437 readPrimordialConfiguration = true; 438 try { 439 readConfiguration(); 440 441 // Platform loggers begin to delegate to java.util.logging.Logger 442 jdk.internal.logger.BootstrapLogger.redirectTemporaryLoggers(); 443 444 } catch (Exception ex) { 445 assert false : "Exception raised while reading logging configuration: " + ex; 446 } 447 } 448 } 449 450 // LoggerContext maps from AppContext 451 private WeakHashMap<Object, LoggerContext> contextsMap = null; 452 453 // Returns the LoggerContext for the user code (i.e. application or AppContext). 454 // Loggers are isolated from each AppContext. 455 private LoggerContext getUserContext() { 456 LoggerContext context = null; 457 458 SecurityManager sm = System.getSecurityManager(); 459 JavaAWTAccess javaAwtAccess = SharedSecrets.getJavaAWTAccess(); 460 if (sm != null && javaAwtAccess != null) { 461 // for each applet, it has its own LoggerContext isolated from others 462 final Object ecx = javaAwtAccess.getAppletContext(); 463 if (ecx != null) { 464 synchronized (javaAwtAccess) { 465 // find the AppContext of the applet code 466 // will be null if we are in the main app context. 467 if (contextsMap == null) { 468 contextsMap = new WeakHashMap<>(); 469 } 470 context = contextsMap.get(ecx); 471 if (context == null) { 472 // Create a new LoggerContext for the applet. 473 context = new LoggerContext(); 474 contextsMap.put(ecx, context); 475 } 476 } 477 } 478 } 479 // for standalone app, return userContext 480 return context != null ? context : userContext; 481 } 482 483 // The system context. 484 final LoggerContext getSystemContext() { 485 return systemContext; 486 } 487 488 private List<LoggerContext> contexts() { 489 List<LoggerContext> cxs = new ArrayList<>(); 490 cxs.add(getSystemContext()); 491 cxs.add(getUserContext()); 492 return cxs; 493 } 494 495 // Find or create a specified logger instance. If a logger has 496 // already been created with the given name it is returned. 497 // Otherwise a new logger instance is created and registered 498 // in the LogManager global namespace. 499 // This method will always return a non-null Logger object. 500 // Synchronization is not required here. All synchronization for 501 // adding a new Logger object is handled by addLogger(). 502 // 503 // This method must delegate to the LogManager implementation to 504 // add a new Logger or return the one that has been added previously 505 // as a LogManager subclass may override the addLogger, getLogger, 506 // readConfiguration, and other methods. 507 Logger demandLogger(String name, String resourceBundleName, Class<?> caller) { 508 Logger result = getLogger(name); 509 if (result == null) { 510 // only allocate the new logger once 511 Logger newLogger = new Logger(name, resourceBundleName, caller, this, false); 512 do { 513 if (addLogger(newLogger)) { 514 // We successfully added the new Logger that we 515 // created above so return it without refetching. 516 return newLogger; 517 } 518 519 // We didn't add the new Logger that we created above 520 // because another thread added a Logger with the same 521 // name after our null check above and before our call 522 // to addLogger(). We have to refetch the Logger because 523 // addLogger() returns a boolean instead of the Logger 524 // reference itself. However, if the thread that created 525 // the other Logger is not holding a strong reference to 526 // the other Logger, then it is possible for the other 527 // Logger to be GC'ed after we saw it in addLogger() and 528 // before we can refetch it. If it has been GC'ed then 529 // we'll just loop around and try again. 530 result = getLogger(name); 531 } while (result == null); 532 } 533 return result; 534 } 535 536 Logger demandSystemLogger(String name, String resourceBundleName, Class<?> caller) { 537 // Add a system logger in the system context's namespace 538 final Logger sysLogger = getSystemContext() 539 .demandLogger(name, resourceBundleName, caller); 540 541 // Add the system logger to the LogManager's namespace if not exist 542 // so that there is only one single logger of the given name. 543 // System loggers are visible to applications unless a logger of 544 // the same name has been added. 545 Logger logger; 546 do { 547 // First attempt to call addLogger instead of getLogger 548 // This would avoid potential bug in custom LogManager.getLogger 549 // implementation that adds a logger if does not exist 550 if (addLogger(sysLogger)) { 551 // successfully added the new system logger 552 logger = sysLogger; 553 } else { 554 logger = getLogger(name); 555 } 556 } while (logger == null); 557 558 // LogManager will set the sysLogger's handlers via LogManager.addLogger method. 559 if (logger != sysLogger && sysLogger.accessCheckedHandlers().length == 0) { 560 // if logger already exists but handlers not set 561 final Logger l = logger; 562 AccessController.doPrivileged(new PrivilegedAction<Void>() { 563 @Override 564 public Void run() { 565 for (Handler hdl : l.accessCheckedHandlers()) { 566 sysLogger.addHandler(hdl); 567 } 568 return null; 569 } 570 }); 571 } 572 return sysLogger; 573 } 574 575 // LoggerContext maintains the logger namespace per context. 576 // The default LogManager implementation has one system context and user 577 // context. The system context is used to maintain the namespace for 578 // all system loggers and is queried by the system code. If a system logger 579 // doesn't exist in the user context, it'll also be added to the user context. 580 // The user context is queried by the user code and all other loggers are 581 // added in the user context. 582 class LoggerContext { 583 // Table of named Loggers that maps names to Loggers. 584 private final ConcurrentHashMap<String,LoggerWeakRef> namedLoggers = 585 new ConcurrentHashMap<>(); 586 // Tree of named Loggers 587 private final LogNode root; 588 private LoggerContext() { 589 this.root = new LogNode(null, this); 590 } 591 592 593 // Tells whether default loggers are required in this context. 594 // If true, the default loggers will be lazily added. 595 final boolean requiresDefaultLoggers() { 596 final boolean requiresDefaultLoggers = (getOwner() == manager); 597 if (requiresDefaultLoggers) { 598 getOwner().ensureLogManagerInitialized(); 599 } 600 return requiresDefaultLoggers; 601 } 602 603 // This context's LogManager. 604 final LogManager getOwner() { 605 return LogManager.this; 606 } 607 608 // This context owner's root logger, which if not null, and if 609 // the context requires default loggers, will be added to the context 610 // logger's tree. 611 final Logger getRootLogger() { 612 return getOwner().rootLogger; 613 } 614 615 // The global logger, which if not null, and if 616 // the context requires default loggers, will be added to the context 617 // logger's tree. 618 final Logger getGlobalLogger() { 619 @SuppressWarnings("deprecation") // avoids initialization cycles. 620 final Logger global = Logger.global; 621 return global; 622 } 623 624 Logger demandLogger(String name, String resourceBundleName, Class<?> caller) { 625 // a LogManager subclass may have its own implementation to add and 626 // get a Logger. So delegate to the LogManager to do the work. 627 final LogManager owner = getOwner(); 628 return owner.demandLogger(name, resourceBundleName, caller); 629 } 630 631 632 // Due to subtle deadlock issues getUserContext() no longer 633 // calls addLocalLogger(rootLogger); 634 // Therefore - we need to add the default loggers later on. 635 // Checks that the context is properly initialized 636 // This is necessary before calling e.g. find(name) 637 // or getLoggerNames() 638 // 639 private void ensureInitialized() { 640 if (requiresDefaultLoggers()) { 641 // Ensure that the root and global loggers are set. 642 ensureDefaultLogger(getRootLogger()); 643 ensureDefaultLogger(getGlobalLogger()); 644 } 645 } 646 647 648 Logger findLogger(String name) { 649 // Attempt to find logger without locking. 650 LoggerWeakRef ref = namedLoggers.get(name); 651 Logger logger = ref == null ? null : ref.get(); 652 653 // if logger is not null, then we can return it right away. 654 // if name is "" or "global" and logger is null 655 // we need to fall through and check that this context is 656 // initialized. 657 // if ref is not null and logger is null we also need to 658 // fall through. 659 if (logger != null || (ref == null && !name.isEmpty() 660 && !name.equals(Logger.GLOBAL_LOGGER_NAME))) { 661 return logger; 662 } 663 664 // We either found a stale reference, or we were looking for 665 // "" or "global" and didn't find them. 666 // Make sure context is initialized (has the default loggers), 667 // and look up again, cleaning the stale reference if it hasn't 668 // been cleaned up in between. All this needs to be done inside 669 // a synchronized block. 670 synchronized(this) { 671 // ensure that this context is properly initialized before 672 // looking for loggers. 673 ensureInitialized(); 674 ref = namedLoggers.get(name); 675 if (ref == null) { 676 return null; 677 } 678 logger = ref.get(); 679 if (logger == null) { 680 // The namedLoggers map holds stale weak reference 681 // to a logger which has been GC-ed. 682 ref.dispose(); 683 } 684 return logger; 685 } 686 } 687 688 // This method is called before adding a logger to the 689 // context. 690 // 'logger' is the context that will be added. 691 // This method will ensure that the defaults loggers are added 692 // before adding 'logger'. 693 // 694 private void ensureAllDefaultLoggers(Logger logger) { 695 if (requiresDefaultLoggers()) { 696 final String name = logger.getName(); 697 if (!name.isEmpty()) { 698 ensureDefaultLogger(getRootLogger()); 699 if (!Logger.GLOBAL_LOGGER_NAME.equals(name)) { 700 ensureDefaultLogger(getGlobalLogger()); 701 } 702 } 703 } 704 } 705 706 private void ensureDefaultLogger(Logger logger) { 707 // Used for lazy addition of root logger and global logger 708 // to a LoggerContext. 709 710 // This check is simple sanity: we do not want that this 711 // method be called for anything else than Logger.global 712 // or owner.rootLogger. 713 if (!requiresDefaultLoggers() || logger == null 714 || logger != getGlobalLogger() && logger != LogManager.this.rootLogger ) { 715 716 // the case where we have a non null logger which is neither 717 // Logger.global nor manager.rootLogger indicates a serious 718 // issue - as ensureDefaultLogger should never be called 719 // with any other loggers than one of these two (or null - if 720 // e.g manager.rootLogger is not yet initialized)... 721 assert logger == null; 722 723 return; 724 } 725 726 // Adds the logger if it's not already there. 727 if (!namedLoggers.containsKey(logger.getName())) { 728 // It is important to prevent addLocalLogger to 729 // call ensureAllDefaultLoggers when we're in the process 730 // off adding one of those default loggers - as this would 731 // immediately cause a stack overflow. 732 // Therefore we must pass addDefaultLoggersIfNeeded=false, 733 // even if requiresDefaultLoggers is true. 734 addLocalLogger(logger, false); 735 } 736 } 737 738 boolean addLocalLogger(Logger logger) { 739 // no need to add default loggers if it's not required 740 return addLocalLogger(logger, requiresDefaultLoggers()); 741 } 742 743 // Add a logger to this context. This method will only set its level 744 // and process parent loggers. It doesn't set its handlers. 745 synchronized boolean addLocalLogger(Logger logger, boolean addDefaultLoggersIfNeeded) { 746 // addDefaultLoggersIfNeeded serves to break recursion when adding 747 // default loggers. If we're adding one of the default loggers 748 // (we're being called from ensureDefaultLogger()) then 749 // addDefaultLoggersIfNeeded will be false: we don't want to 750 // call ensureAllDefaultLoggers again. 751 // 752 // Note: addDefaultLoggersIfNeeded can also be false when 753 // requiresDefaultLoggers is false - since calling 754 // ensureAllDefaultLoggers would have no effect in this case. 755 if (addDefaultLoggersIfNeeded) { 756 ensureAllDefaultLoggers(logger); 757 } 758 759 final String name = logger.getName(); 760 if (name == null) { 761 throw new NullPointerException(); 762 } 763 LoggerWeakRef ref = namedLoggers.get(name); 764 if (ref != null) { 765 if (ref.get() == null) { 766 // It's possible that the Logger was GC'ed after a 767 // drainLoggerRefQueueBounded() call above so allow 768 // a new one to be registered. 769 ref.dispose(); 770 } else { 771 // We already have a registered logger with the given name. 772 return false; 773 } 774 } 775 776 // We're adding a new logger. 777 // Note that we are creating a weak reference here. 778 final LogManager owner = getOwner(); 779 logger.setLogManager(owner); 780 ref = owner.new LoggerWeakRef(logger); 781 782 // Apply any initial level defined for the new logger, unless 783 // the logger's level is already initialized 784 Level level = owner.getLevelProperty(name + ".level", null); 785 if (level != null && !logger.isLevelInitialized()) { 786 doSetLevel(logger, level); 787 } 788 789 // instantiation of the handler is done in the LogManager.addLogger 790 // implementation as a handler class may be only visible to LogManager 791 // subclass for the custom log manager case 792 processParentHandlers(logger, name, VisitedLoggers.NEVER); 793 794 // Find the new node and its parent. 795 LogNode node = getNode(name); 796 node.loggerRef = ref; 797 Logger parent = null; 798 LogNode nodep = node.parent; 799 while (nodep != null) { 800 LoggerWeakRef nodeRef = nodep.loggerRef; 801 if (nodeRef != null) { 802 parent = nodeRef.get(); 803 if (parent != null) { 804 break; 805 } 806 } 807 nodep = nodep.parent; 808 } 809 810 if (parent != null) { 811 doSetParent(logger, parent); 812 } 813 // Walk over the children and tell them we are their new parent. 814 node.walkAndSetParent(logger); 815 // new LogNode is ready so tell the LoggerWeakRef about it 816 ref.setNode(node); 817 818 // Do not publish 'ref' in namedLoggers before the logger tree 819 // is fully updated - because the named logger will be visible as 820 // soon as it is published in namedLoggers (findLogger takes 821 // benefit of the ConcurrentHashMap implementation of namedLoggers 822 // to avoid synchronizing on retrieval when that is possible). 823 namedLoggers.put(name, ref); 824 return true; 825 } 826 827 void removeLoggerRef(String name, LoggerWeakRef ref) { 828 namedLoggers.remove(name, ref); 829 } 830 831 synchronized Enumeration<String> getLoggerNames() { 832 // ensure that this context is properly initialized before 833 // returning logger names. 834 ensureInitialized(); 835 return Collections.enumeration(namedLoggers.keySet()); 836 } 837 838 // If logger.getUseParentHandlers() returns 'true' and any of the logger's 839 // parents have levels or handlers defined, make sure they are instantiated. 840 private void processParentHandlers(final Logger logger, final String name, 841 Predicate<Logger> visited) { 842 final LogManager owner = getOwner(); 843 AccessController.doPrivileged(new PrivilegedAction<Void>() { 844 @Override 845 public Void run() { 846 if (logger != owner.rootLogger) { 847 boolean useParent = owner.getBooleanProperty(name + ".useParentHandlers", true); 848 if (!useParent) { 849 logger.setUseParentHandlers(false); 850 } 851 } 852 return null; 853 } 854 }); 855 856 int ix = 1; 857 for (;;) { 858 int ix2 = name.indexOf('.', ix); 859 if (ix2 < 0) { 860 break; 861 } 862 String pname = name.substring(0, ix2); 863 if (owner.getProperty(pname + ".level") != null || 864 owner.getProperty(pname + ".handlers") != null) { 865 // This pname has a level/handlers definition. 866 // Make sure it exists. 867 if (visited.test(demandLogger(pname, null, null))) { 868 break; 869 } 870 } 871 ix = ix2+1; 872 } 873 } 874 875 // Gets a node in our tree of logger nodes. 876 // If necessary, create it. 877 LogNode getNode(String name) { 878 if (name == null || name.equals("")) { 879 return root; 880 } 881 LogNode node = root; 882 while (name.length() > 0) { 883 int ix = name.indexOf('.'); 884 String head; 885 if (ix > 0) { 886 head = name.substring(0, ix); 887 name = name.substring(ix + 1); 888 } else { 889 head = name; 890 name = ""; 891 } 892 if (node.children == null) { 893 node.children = new HashMap<>(); 894 } 895 LogNode child = node.children.get(head); 896 if (child == null) { 897 child = new LogNode(node, this); 898 node.children.put(head, child); 899 } 900 node = child; 901 } 902 return node; 903 } 904 } 905 906 final class SystemLoggerContext extends LoggerContext { 907 // Add a system logger in the system context's namespace as well as 908 // in the LogManager's namespace if not exist so that there is only 909 // one single logger of the given name. System loggers are visible 910 // to applications unless a logger of the same name has been added. 911 @Override 912 Logger demandLogger(String name, String resourceBundleName, Class<?> caller) { 913 Logger result = findLogger(name); 914 if (result == null) { 915 // only allocate the new system logger once 916 Logger newLogger = new Logger(name, resourceBundleName, caller, getOwner(), true); 917 do { 918 if (addLocalLogger(newLogger)) { 919 // We successfully added the new Logger that we 920 // created above so return it without refetching. 921 result = newLogger; 922 } else { 923 // We didn't add the new Logger that we created above 924 // because another thread added a Logger with the same 925 // name after our null check above and before our call 926 // to addLogger(). We have to refetch the Logger because 927 // addLogger() returns a boolean instead of the Logger 928 // reference itself. However, if the thread that created 929 // the other Logger is not holding a strong reference to 930 // the other Logger, then it is possible for the other 931 // Logger to be GC'ed after we saw it in addLogger() and 932 // before we can refetch it. If it has been GC'ed then 933 // we'll just loop around and try again. 934 result = findLogger(name); 935 } 936 } while (result == null); 937 } 938 return result; 939 } 940 } 941 942 // Add new per logger handlers. 943 // We need to raise privilege here. All our decisions will 944 // be made based on the logging configuration, which can 945 // only be modified by trusted code. 946 private void loadLoggerHandlers(final Logger logger, final String name, 947 final String handlersPropertyName) 948 { 949 AccessController.doPrivileged(new PrivilegedAction<Void>() { 950 @Override 951 public Void run() { 952 setLoggerHandlers(logger, name, handlersPropertyName, 953 createLoggerHandlers(name, handlersPropertyName)); 954 return null; 955 } 956 }); 957 } 958 959 private void setLoggerHandlers(final Logger logger, final String name, 960 final String handlersPropertyName, 961 List<Handler> handlers) 962 { 963 final boolean ensureCloseOnReset = ! handlers.isEmpty() 964 && getBooleanProperty(handlersPropertyName + ".ensureCloseOnReset",true); 965 int count = 0; 966 for (Handler hdl : handlers) { 967 logger.addHandler(hdl); 968 if (++count == 1 && ensureCloseOnReset) { 969 // add this logger to the closeOnResetLoggers list. 970 closeOnResetLoggers.addIfAbsent(CloseOnReset.create(logger)); 971 } 972 } 973 } 974 975 private List<Handler> createLoggerHandlers(final String name, final String handlersPropertyName) 976 { 977 String names[] = parseClassNames(handlersPropertyName); 978 List<Handler> handlers = new ArrayList<>(names.length); 979 for (String type : names) { 980 try { 981 @SuppressWarnings("deprecation") 982 Object o = ClassLoader.getSystemClassLoader().loadClass(type).newInstance(); 983 Handler hdl = (Handler) o; 984 // Check if there is a property defining the 985 // this handler's level. 986 String levs = getProperty(type + ".level"); 987 if (levs != null) { 988 Level l = Level.findLevel(levs); 989 if (l != null) { 990 hdl.setLevel(l); 991 } else { 992 // Probably a bad level. Drop through. 993 System.err.println("Can't set level for " + type); 994 } 995 } 996 // Add this Handler to the logger 997 handlers.add(hdl); 998 } catch (Exception ex) { 999 System.err.println("Can't load log handler \"" + type + "\""); 1000 System.err.println("" + ex); 1001 ex.printStackTrace(); 1002 } 1003 } 1004 1005 return handlers; 1006 } 1007 1008 1009 // loggerRefQueue holds LoggerWeakRef objects for Logger objects 1010 // that have been GC'ed. 1011 private final ReferenceQueue<Logger> loggerRefQueue 1012 = new ReferenceQueue<>(); 1013 1014 // Package-level inner class. 1015 // Helper class for managing WeakReferences to Logger objects. 1016 // 1017 // LogManager.namedLoggers 1018 // - has weak references to all named Loggers 1019 // - namedLoggers keeps the LoggerWeakRef objects for the named 1020 // Loggers around until we can deal with the book keeping for 1021 // the named Logger that is being GC'ed. 1022 // LogManager.LogNode.loggerRef 1023 // - has a weak reference to a named Logger 1024 // - the LogNode will also keep the LoggerWeakRef objects for 1025 // the named Loggers around; currently LogNodes never go away. 1026 // Logger.kids 1027 // - has a weak reference to each direct child Logger; this 1028 // includes anonymous and named Loggers 1029 // - anonymous Loggers are always children of the rootLogger 1030 // which is a strong reference; rootLogger.kids keeps the 1031 // LoggerWeakRef objects for the anonymous Loggers around 1032 // until we can deal with the book keeping. 1033 // 1034 final class LoggerWeakRef extends WeakReference<Logger> { 1035 private String name; // for namedLoggers cleanup 1036 private LogNode node; // for loggerRef cleanup 1037 private WeakReference<Logger> parentRef; // for kids cleanup 1038 private boolean disposed = false; // avoid calling dispose twice 1039 1040 LoggerWeakRef(Logger logger) { 1041 super(logger, loggerRefQueue); 1042 1043 name = logger.getName(); // save for namedLoggers cleanup 1044 } 1045 1046 // dispose of this LoggerWeakRef object 1047 void dispose() { 1048 // Avoid calling dispose twice. When a Logger is gc'ed, its 1049 // LoggerWeakRef will be enqueued. 1050 // However, a new logger of the same name may be added (or looked 1051 // up) before the queue is drained. When that happens, dispose() 1052 // will be called by addLocalLogger() or findLogger(). 1053 // Later when the queue is drained, dispose() will be called again 1054 // for the same LoggerWeakRef. Marking LoggerWeakRef as disposed 1055 // avoids processing the data twice (even though the code should 1056 // now be reentrant). 1057 synchronized(this) { 1058 // Note to maintainers: 1059 // Be careful not to call any method that tries to acquire 1060 // another lock from within this block - as this would surely 1061 // lead to deadlocks, given that dispose() can be called by 1062 // multiple threads, and from within different synchronized 1063 // methods/blocks. 1064 if (disposed) return; 1065 disposed = true; 1066 } 1067 1068 final LogNode n = node; 1069 if (n != null) { 1070 // n.loggerRef can only be safely modified from within 1071 // a lock on LoggerContext. removeLoggerRef is already 1072 // synchronized on LoggerContext so calling 1073 // n.context.removeLoggerRef from within this lock is safe. 1074 synchronized (n.context) { 1075 // if we have a LogNode, then we were a named Logger 1076 // so clear namedLoggers weak ref to us 1077 n.context.removeLoggerRef(name, this); 1078 name = null; // clear our ref to the Logger's name 1079 1080 // LogNode may have been reused - so only clear 1081 // LogNode.loggerRef if LogNode.loggerRef == this 1082 if (n.loggerRef == this) { 1083 n.loggerRef = null; // clear LogNode's weak ref to us 1084 } 1085 node = null; // clear our ref to LogNode 1086 } 1087 } 1088 1089 if (parentRef != null) { 1090 // this LoggerWeakRef has or had a parent Logger 1091 Logger parent = parentRef.get(); 1092 if (parent != null) { 1093 // the parent Logger is still there so clear the 1094 // parent Logger's weak ref to us 1095 parent.removeChildLogger(this); 1096 } 1097 parentRef = null; // clear our weak ref to the parent Logger 1098 } 1099 } 1100 1101 // set the node field to the specified value 1102 void setNode(LogNode node) { 1103 this.node = node; 1104 } 1105 1106 // set the parentRef field to the specified value 1107 void setParentRef(WeakReference<Logger> parentRef) { 1108 this.parentRef = parentRef; 1109 } 1110 } 1111 1112 // Package-level method. 1113 // Drain some Logger objects that have been GC'ed. 1114 // 1115 // drainLoggerRefQueueBounded() is called by addLogger() below 1116 // and by Logger.getAnonymousLogger(String) so we'll drain up to 1117 // MAX_ITERATIONS GC'ed Loggers for every Logger we add. 1118 // 1119 // On a WinXP VMware client, a MAX_ITERATIONS value of 400 gives 1120 // us about a 50/50 mix in increased weak ref counts versus 1121 // decreased weak ref counts in the AnonLoggerWeakRefLeak test. 1122 // Here are stats for cleaning up sets of 400 anonymous Loggers: 1123 // - test duration 1 minute 1124 // - sample size of 125 sets of 400 1125 // - average: 1.99 ms 1126 // - minimum: 0.57 ms 1127 // - maximum: 25.3 ms 1128 // 1129 // The same config gives us a better decreased weak ref count 1130 // than increased weak ref count in the LoggerWeakRefLeak test. 1131 // Here are stats for cleaning up sets of 400 named Loggers: 1132 // - test duration 2 minutes 1133 // - sample size of 506 sets of 400 1134 // - average: 0.57 ms 1135 // - minimum: 0.02 ms 1136 // - maximum: 10.9 ms 1137 // 1138 private final static int MAX_ITERATIONS = 400; 1139 final void drainLoggerRefQueueBounded() { 1140 for (int i = 0; i < MAX_ITERATIONS; i++) { 1141 if (loggerRefQueue == null) { 1142 // haven't finished loading LogManager yet 1143 break; 1144 } 1145 1146 LoggerWeakRef ref = (LoggerWeakRef) loggerRefQueue.poll(); 1147 if (ref == null) { 1148 break; 1149 } 1150 // a Logger object has been GC'ed so clean it up 1151 ref.dispose(); 1152 } 1153 } 1154 1155 /** 1156 * Add a named logger. This does nothing and returns false if a logger 1157 * with the same name is already registered. 1158 * <p> 1159 * The Logger factory methods call this method to register each 1160 * newly created Logger. 1161 * <p> 1162 * The application should retain its own reference to the Logger 1163 * object to avoid it being garbage collected. The LogManager 1164 * may only retain a weak reference. 1165 * 1166 * @param logger the new logger. 1167 * @return true if the argument logger was registered successfully, 1168 * false if a logger of that name already exists. 1169 * @exception NullPointerException if the logger name is null. 1170 */ 1171 public boolean addLogger(Logger logger) { 1172 final String name = logger.getName(); 1173 if (name == null) { 1174 throw new NullPointerException(); 1175 } 1176 drainLoggerRefQueueBounded(); 1177 LoggerContext cx = getUserContext(); 1178 if (cx.addLocalLogger(logger)) { 1179 // Do we have a per logger handler too? 1180 // Note: this will add a 200ms penalty 1181 loadLoggerHandlers(logger, name, name + ".handlers"); 1182 return true; 1183 } else { 1184 return false; 1185 } 1186 } 1187 1188 // Private method to set a level on a logger. 1189 // If necessary, we raise privilege before doing the call. 1190 private static void doSetLevel(final Logger logger, final Level level) { 1191 SecurityManager sm = System.getSecurityManager(); 1192 if (sm == null) { 1193 // There is no security manager, so things are easy. 1194 logger.setLevel(level); 1195 return; 1196 } 1197 // There is a security manager. Raise privilege before 1198 // calling setLevel. 1199 AccessController.doPrivileged(new PrivilegedAction<Object>() { 1200 @Override 1201 public Object run() { 1202 logger.setLevel(level); 1203 return null; 1204 }}); 1205 } 1206 1207 // Private method to set a parent on a logger. 1208 // If necessary, we raise privilege before doing the setParent call. 1209 private static void doSetParent(final Logger logger, final Logger parent) { 1210 SecurityManager sm = System.getSecurityManager(); 1211 if (sm == null) { 1212 // There is no security manager, so things are easy. 1213 logger.setParent(parent); 1214 return; 1215 } 1216 // There is a security manager. Raise privilege before 1217 // calling setParent. 1218 AccessController.doPrivileged(new PrivilegedAction<Object>() { 1219 @Override 1220 public Object run() { 1221 logger.setParent(parent); 1222 return null; 1223 }}); 1224 } 1225 1226 /** 1227 * Method to find a named logger. 1228 * <p> 1229 * Note that since untrusted code may create loggers with 1230 * arbitrary names this method should not be relied on to 1231 * find Loggers for security sensitive logging. 1232 * It is also important to note that the Logger associated with the 1233 * String {@code name} may be garbage collected at any time if there 1234 * is no strong reference to the Logger. The caller of this method 1235 * must check the return value for null in order to properly handle 1236 * the case where the Logger has been garbage collected. 1237 * 1238 * @param name name of the logger 1239 * @return matching logger or null if none is found 1240 */ 1241 public Logger getLogger(String name) { 1242 return getUserContext().findLogger(name); 1243 } 1244 1245 /** 1246 * Get an enumeration of known logger names. 1247 * <p> 1248 * Note: Loggers may be added dynamically as new classes are loaded. 1249 * This method only reports on the loggers that are currently registered. 1250 * It is also important to note that this method only returns the name 1251 * of a Logger, not a strong reference to the Logger itself. 1252 * The returned String does nothing to prevent the Logger from being 1253 * garbage collected. In particular, if the returned name is passed 1254 * to {@code LogManager.getLogger()}, then the caller must check the 1255 * return value from {@code LogManager.getLogger()} for null to properly 1256 * handle the case where the Logger has been garbage collected in the 1257 * time since its name was returned by this method. 1258 * 1259 * @return enumeration of logger name strings 1260 */ 1261 public Enumeration<String> getLoggerNames() { 1262 return getUserContext().getLoggerNames(); 1263 } 1264 1265 /** 1266 * Reads and initializes the logging configuration. 1267 * <p> 1268 * If the "java.util.logging.config.class" system property is set, then the 1269 * property value is treated as a class name. The given class will be 1270 * loaded, an object will be instantiated, and that object's constructor 1271 * is responsible for reading in the initial configuration. (That object 1272 * may use other system properties to control its configuration.) The 1273 * alternate configuration class can use {@code readConfiguration(InputStream)} 1274 * to define properties in the LogManager. 1275 * <p> 1276 * If "java.util.logging.config.class" system property is <b>not</b> set, 1277 * then this method will read the initial configuration from a properties 1278 * file and calls the {@link #readConfiguration(InputStream)} method to initialize 1279 * the configuration. The "java.util.logging.config.file" system property can be used 1280 * to specify the properties file that will be read as the initial configuration; 1281 * if not set, then the LogManager default configuration is used. 1282 * The default configuration is typically loaded from the 1283 * properties file "{@code conf/logging.properties}" in the Java installation 1284 * directory. 1285 * 1286 * <p> 1287 * Any {@linkplain #addConfigurationListener registered configuration 1288 * listener} will be invoked after the properties are read. 1289 * 1290 * @apiNote This {@code readConfiguration} method should only be used for 1291 * initializing the configuration during LogManager initialization or 1292 * used with the "java.util.logging.config.class" property. 1293 * When this method is called after loggers have been created, and 1294 * the "java.util.logging.config.class" system property is not set, all 1295 * existing loggers will be {@linkplain #reset() reset}. Then any 1296 * existing loggers that have a level property specified in the new 1297 * configuration stream will be {@linkplain 1298 * Logger#setLevel(java.util.logging.Level) set} to the specified log level. 1299 * <p> 1300 * To properly update the logging configuration, use the 1301 * {@link #updateConfiguration(java.util.function.Function)} or 1302 * {@link #updateConfiguration(java.io.InputStream, java.util.function.Function)} 1303 * methods instead. 1304 * 1305 * @throws SecurityException if a security manager exists and if 1306 * the caller does not have LoggingPermission("control"). 1307 * @throws IOException if there are IO problems reading the configuration. 1308 */ 1309 public void readConfiguration() throws IOException, SecurityException { 1310 checkPermission(); 1311 1312 // if a configuration class is specified, load it and use it. 1313 String cname = System.getProperty("java.util.logging.config.class"); 1314 if (cname != null) { 1315 try { 1316 // Instantiate the named class. It is its constructor's 1317 // responsibility to initialize the logging configuration, by 1318 // calling readConfiguration(InputStream) with a suitable stream. 1319 try { 1320 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(cname); 1321 @SuppressWarnings("deprecation") 1322 Object witness = clz.newInstance(); 1323 return; 1324 } catch (ClassNotFoundException ex) { 1325 Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(cname); 1326 @SuppressWarnings("deprecation") 1327 Object witness = clz.newInstance(); 1328 return; 1329 } 1330 } catch (Exception ex) { 1331 System.err.println("Logging configuration class \"" + cname + "\" failed"); 1332 System.err.println("" + ex); 1333 // keep going and useful config file. 1334 } 1335 } 1336 1337 String fname = getConfigurationFileName(); 1338 try (final InputStream in = new FileInputStream(fname)) { 1339 final BufferedInputStream bin = new BufferedInputStream(in); 1340 readConfiguration(bin); 1341 } 1342 } 1343 1344 String getConfigurationFileName() throws IOException { 1345 String fname = System.getProperty("java.util.logging.config.file"); 1346 if (fname == null) { 1347 fname = System.getProperty("java.home"); 1348 if (fname == null) { 1349 throw new Error("Can't find java.home ??"); 1350 } 1351 fname = Paths.get(fname, "conf", "logging.properties") 1352 .toAbsolutePath().normalize().toString(); 1353 } 1354 return fname; 1355 } 1356 1357 /** 1358 * Reset the logging configuration. 1359 * <p> 1360 * For all named loggers, the reset operation removes and closes 1361 * all Handlers and (except for the root logger) sets the level 1362 * to {@code null}. The root logger's level is set to {@code Level.INFO}. 1363 * 1364 * @apiNote Calling this method also clears the LogManager {@linkplain 1365 * #getProperty(java.lang.String) properties}. The {@link 1366 * #updateConfiguration(java.util.function.Function) 1367 * updateConfiguration(Function)} or 1368 * {@link #updateConfiguration(java.io.InputStream, java.util.function.Function) 1369 * updateConfiguration(InputStream, Function)} method can be used to 1370 * properly update to a new configuration. 1371 * 1372 * @throws SecurityException if a security manager exists and if 1373 * the caller does not have LoggingPermission("control"). 1374 */ 1375 1376 public void reset() throws SecurityException { 1377 checkPermission(); 1378 1379 List<CloseOnReset> persistent; 1380 1381 // We don't want reset() and readConfiguration() 1382 // to run in parallel 1383 configurationLock.lock(); 1384 try { 1385 // install new empty properties 1386 props = new Properties(); 1387 // make sure we keep the loggers persistent until reset is done. 1388 // Those are the loggers for which we previously created a 1389 // handler from the configuration, and we need to prevent them 1390 // from being gc'ed until those handlers are closed. 1391 persistent = new ArrayList<>(closeOnResetLoggers); 1392 closeOnResetLoggers.clear(); 1393 1394 // if reset has been called from shutdown-hook (Cleaner), 1395 // or if reset has been called from readConfiguration() which 1396 // already holds the lock and will change the state itself, 1397 // then do not change state here... 1398 if (globalHandlersState != STATE_SHUTDOWN && 1399 globalHandlersState != STATE_READING_CONFIG) { 1400 // ...else user called reset()... 1401 // Since we are doing a reset we no longer want to initialize 1402 // the global handlers, if they haven't been initialized yet. 1403 globalHandlersState = STATE_INITIALIZED; 1404 } 1405 1406 for (LoggerContext cx : contexts()) { 1407 resetLoggerContext(cx); 1408 } 1409 1410 persistent.clear(); 1411 } finally { 1412 configurationLock.unlock(); 1413 } 1414 } 1415 1416 private void resetLoggerContext(LoggerContext cx) { 1417 Enumeration<String> enum_ = cx.getLoggerNames(); 1418 while (enum_.hasMoreElements()) { 1419 String name = enum_.nextElement(); 1420 Logger logger = cx.findLogger(name); 1421 if (logger != null) { 1422 resetLogger(logger); 1423 } 1424 } 1425 } 1426 1427 private void closeHandlers(Logger logger) { 1428 Handler[] targets = logger.getHandlers(); 1429 for (Handler h : targets) { 1430 logger.removeHandler(h); 1431 try { 1432 h.close(); 1433 } catch (Exception ex) { 1434 // Problems closing a handler? Keep going... 1435 } 1436 } 1437 } 1438 1439 // Private method to reset an individual target logger. 1440 private void resetLogger(Logger logger) { 1441 // Close all the Logger handlers. 1442 closeHandlers(logger); 1443 1444 // Reset Logger level 1445 String name = logger.getName(); 1446 if (name != null && name.equals("")) { 1447 // This is the root logger. 1448 logger.setLevel(defaultLevel); 1449 } else { 1450 logger.setLevel(null); 1451 } 1452 } 1453 1454 // get a list of whitespace separated classnames from a property. 1455 private String[] parseClassNames(String propertyName) { 1456 String hands = getProperty(propertyName); 1457 if (hands == null) { 1458 return new String[0]; 1459 } 1460 hands = hands.trim(); 1461 int ix = 0; 1462 final List<String> result = new ArrayList<>(); 1463 while (ix < hands.length()) { 1464 int end = ix; 1465 while (end < hands.length()) { 1466 if (Character.isWhitespace(hands.charAt(end))) { 1467 break; 1468 } 1469 if (hands.charAt(end) == ',') { 1470 break; 1471 } 1472 end++; 1473 } 1474 String word = hands.substring(ix, end); 1475 ix = end+1; 1476 word = word.trim(); 1477 if (word.length() == 0) { 1478 continue; 1479 } 1480 result.add(word); 1481 } 1482 return result.toArray(new String[result.size()]); 1483 } 1484 1485 /** 1486 * Reads and initializes the logging configuration from the given input stream. 1487 * 1488 * <p> 1489 * Any {@linkplain #addConfigurationListener registered configuration 1490 * listener} will be invoked after the properties are read. 1491 * 1492 * @apiNote This {@code readConfiguration} method should only be used for 1493 * initializing the configuration during LogManager initialization or 1494 * used with the "java.util.logging.config.class" property. 1495 * When this method is called after loggers have been created, all 1496 * existing loggers will be {@linkplain #reset() reset}. Then any 1497 * existing loggers that have a level property specified in the 1498 * given input stream will be {@linkplain 1499 * Logger#setLevel(java.util.logging.Level) set} to the specified log level. 1500 * <p> 1501 * To properly update the logging configuration, use the 1502 * {@link #updateConfiguration(java.util.function.Function)} or 1503 * {@link #updateConfiguration(java.io.InputStream, java.util.function.Function)} 1504 * method instead. 1505 * 1506 * @param ins stream to read properties from 1507 * @throws SecurityException if a security manager exists and if 1508 * the caller does not have LoggingPermission("control"). 1509 * @throws IOException if there are problems reading from the stream, 1510 * or the given stream is not in the 1511 * {@linkplain java.util.Properties properties file} format. 1512 */ 1513 public void readConfiguration(InputStream ins) throws IOException, SecurityException { 1514 checkPermission(); 1515 1516 // We don't want reset() and readConfiguration() to run 1517 // in parallel. 1518 configurationLock.lock(); 1519 try { 1520 if (globalHandlersState == STATE_SHUTDOWN) { 1521 // already in terminal state: don't even bother 1522 // to read the configuration 1523 return; 1524 } 1525 1526 // change state to STATE_READING_CONFIG to signal reset() to not change it 1527 globalHandlersState = STATE_READING_CONFIG; 1528 try { 1529 // reset configuration which leaves globalHandlersState at STATE_READING_CONFIG 1530 // so that while reading configuration, any ongoing logging requests block and 1531 // wait for the outcome (see the end of this try statement) 1532 reset(); 1533 1534 try { 1535 // Load the properties 1536 props.load(ins); 1537 } catch (IllegalArgumentException x) { 1538 // props.load may throw an IllegalArgumentException if the stream 1539 // contains malformed Unicode escape sequences. 1540 // We wrap that in an IOException as readConfiguration is 1541 // specified to throw IOException if there are problems reading 1542 // from the stream. 1543 // Note: new IOException(x.getMessage(), x) allow us to get a more 1544 // concise error message than new IOException(x); 1545 throw new IOException(x.getMessage(), x); 1546 } 1547 1548 // Instantiate new configuration objects. 1549 String names[] = parseClassNames("config"); 1550 1551 for (String word : names) { 1552 try { 1553 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word); 1554 @SuppressWarnings("deprecation") 1555 Object witness = clz.newInstance(); 1556 } catch (Exception ex) { 1557 System.err.println("Can't load config class \"" + word + "\""); 1558 System.err.println("" + ex); 1559 // ex.printStackTrace(); 1560 } 1561 } 1562 1563 // Set levels on any pre-existing loggers, based on the new properties. 1564 setLevelsOnExistingLoggers(); 1565 1566 // Note that we need to reinitialize global handles when 1567 // they are first referenced. 1568 globalHandlersState = STATE_UNINITIALIZED; 1569 } catch (Throwable t) { 1570 // If there were any trouble, then set state to STATE_INITIALIZED 1571 // so that no global handlers reinitialization is performed on not fully 1572 // initialized configuration. 1573 globalHandlersState = STATE_INITIALIZED; 1574 // re-throw 1575 throw t; 1576 } 1577 } finally { 1578 configurationLock.unlock(); 1579 } 1580 1581 // should be called out of lock to avoid dead-lock situations 1582 // when user code is involved 1583 invokeConfigurationListeners(); 1584 } 1585 1586 // This enum enumerate the configuration properties that will be 1587 // updated on existing loggers when the configuration is updated 1588 // with LogManager.updateConfiguration(). 1589 // 1590 // Note that this works properly only for the global LogManager - as 1591 // Handler and its subclasses get their configuration from 1592 // LogManager.getLogManager(). 1593 // 1594 static enum ConfigProperty { 1595 LEVEL(".level"), HANDLERS(".handlers"), USEPARENT(".useParentHandlers"); 1596 final String suffix; 1597 final int length; 1598 private ConfigProperty(String suffix) { 1599 this.suffix = Objects.requireNonNull(suffix); 1600 length = suffix.length(); 1601 } 1602 1603 public boolean handleKey(String key) { 1604 if (this == HANDLERS && suffix.substring(1).equals(key)) return true; 1605 if (this == HANDLERS && suffix.equals(key)) return false; 1606 return key.endsWith(suffix); 1607 } 1608 String key(String loggerName) { 1609 if (this == HANDLERS && (loggerName == null || loggerName.isEmpty())) { 1610 return suffix.substring(1); 1611 } 1612 return loggerName + suffix; 1613 } 1614 String loggerName(String key) { 1615 assert key.equals(suffix.substring(1)) && this == HANDLERS || key.endsWith(suffix); 1616 if (this == HANDLERS && suffix.substring(1).equals(key)) return ""; 1617 return key.substring(0, key.length() - length); 1618 } 1619 1620 /** 1621 * If the property is one that should be updated on existing loggers by 1622 * updateConfiguration, returns the name of the logger for which the 1623 * property is configured. Otherwise, returns null. 1624 * @param property a property key in 'props' 1625 * @return the name of the logger on which the property is to be set, 1626 * if the property is one that should be updated on existing 1627 * loggers, {@code null} otherwise. 1628 */ 1629 static String getLoggerName(String property) { 1630 for (ConfigProperty p : ConfigProperty.ALL) { 1631 if (p.handleKey(property)) { 1632 return p.loggerName(property); 1633 } 1634 } 1635 return null; // Not a property that should be updated. 1636 } 1637 1638 /** 1639 * Find the ConfigProperty corresponding to the given 1640 * property key (may find none). 1641 * @param property a property key in 'props' 1642 * @return An optional containing a ConfigProperty object, 1643 * if the property is one that should be updated on existing 1644 * loggers, empty otherwise. 1645 */ 1646 static Optional<ConfigProperty> find(String property) { 1647 return ConfigProperty.ALL.stream() 1648 .filter(p -> p.handleKey(property)) 1649 .findFirst(); 1650 } 1651 1652 /** 1653 * Returns true if the given property is one that should be updated 1654 * on existing loggers. 1655 * Used to filter property name streams. 1656 * @param property a property key from the configuration. 1657 * @return true if this property is of interest for updateConfiguration. 1658 */ 1659 static boolean matches(String property) { 1660 return find(property).isPresent(); 1661 } 1662 1663 /** 1664 * Returns true if the new property value is different from the old, 1665 * and therefore needs to be updated on existing loggers. 1666 * @param k a property key in the configuration 1667 * @param previous the old configuration 1668 * @param next the new configuration 1669 * @return true if the property is changing value between the two 1670 * configurations. 1671 */ 1672 static boolean needsUpdating(String k, Properties previous, Properties next) { 1673 final String p = trim(previous.getProperty(k, null)); 1674 final String n = trim(next.getProperty(k, null)); 1675 return ! Objects.equals(p,n); 1676 } 1677 1678 /** 1679 * Applies the mapping function for the given key to the next 1680 * configuration. 1681 * If the mapping function is null then this method does nothing. 1682 * Otherwise, it calls the mapping function to compute the value 1683 * that should be associated with {@code key} in the resulting 1684 * configuration, and applies it to {@code next}. 1685 * If the mapping function returns {@code null} the key is removed 1686 * from {@code next}. 1687 * 1688 * @param k a property key in the configuration 1689 * @param previous the old configuration 1690 * @param next the new configuration (modified by this function) 1691 * @param remappingFunction the mapping function. 1692 */ 1693 static void merge(String k, Properties previous, Properties next, 1694 BiFunction<String, String, String> mappingFunction) { 1695 String p = trim(previous.getProperty(k, null)); 1696 String n = trim(next.getProperty(k, null)); 1697 String mapped = trim(mappingFunction.apply(p,n)); 1698 if (!Objects.equals(n, mapped)) { 1699 if (mapped == null) { 1700 next.remove(k); 1701 } else { 1702 next.setProperty(k, mapped); 1703 } 1704 } 1705 } 1706 1707 private static final EnumSet<ConfigProperty> ALL = 1708 EnumSet.allOf(ConfigProperty.class); 1709 } 1710 1711 // trim the value if not null. 1712 private static String trim(String value) { 1713 return value == null ? null : value.trim(); 1714 } 1715 1716 /** 1717 * An object that keep track of loggers we have already visited. 1718 * Used when updating configuration, to avoid processing the same logger 1719 * twice. 1720 */ 1721 static final class VisitedLoggers implements Predicate<Logger> { 1722 final IdentityHashMap<Logger,Boolean> visited; 1723 private VisitedLoggers(IdentityHashMap<Logger,Boolean> visited) { 1724 this.visited = visited; 1725 } 1726 VisitedLoggers() { 1727 this(new IdentityHashMap<>()); 1728 } 1729 @Override 1730 public boolean test(Logger logger) { 1731 return visited != null && visited.put(logger, Boolean.TRUE) != null; 1732 } 1733 public void clear() { 1734 if (visited != null) visited.clear(); 1735 } 1736 1737 // An object that considers that no logger has ever been visited. 1738 // This is used when processParentHandlers is called from 1739 // LoggerContext.addLocalLogger 1740 static final VisitedLoggers NEVER = new VisitedLoggers(null); 1741 } 1742 1743 1744 /** 1745 * Type of the modification for a given property. One of SAME, ADDED, CHANGED, 1746 * or REMOVED. 1747 */ 1748 static enum ModType { 1749 SAME, // property had no value in the old and new conf, or had the 1750 // same value in both. 1751 ADDED, // property had no value in the old conf, but has one in the new. 1752 CHANGED, // property has a different value in the old conf and the new conf. 1753 REMOVED; // property has no value in the new conf, but had one in the old. 1754 static ModType of(String previous, String next) { 1755 if (previous == null && next != null) { 1756 return ADDED; 1757 } 1758 if (next == null && previous != null) { 1759 return REMOVED; 1760 } 1761 if (!Objects.equals(trim(previous), trim(next))) { 1762 return CHANGED; 1763 } 1764 return SAME; 1765 } 1766 } 1767 1768 /** 1769 * Updates the logging configuration. 1770 * <p> 1771 * If the "java.util.logging.config.file" system property is set, 1772 * then the property value specifies the properties file to be read 1773 * as the new configuration. Otherwise, the LogManager default 1774 * configuration is used. 1775 * <br>The default configuration is typically loaded from the 1776 * properties file "{@code conf/logging.properties}" in the 1777 * Java installation directory. 1778 * <p> 1779 * This method reads the new configuration and calls the {@link 1780 * #updateConfiguration(java.io.InputStream, java.util.function.Function) 1781 * updateConfiguration(ins, mapper)} method to 1782 * update the configuration. 1783 * 1784 * @apiNote 1785 * This method updates the logging configuration from reading 1786 * a properties file and ignores the "java.util.logging.config.class" 1787 * system property. The "java.util.logging.config.class" property is 1788 * only used by the {@link #readConfiguration()} method to load a custom 1789 * configuration class as an initial configuration. 1790 * 1791 * @param mapper a functional interface that takes a configuration 1792 * key <i>k</i> and returns a function <i>f(o,n)</i> whose returned 1793 * value will be applied to the resulting configuration. The 1794 * function <i>f</i> may return {@code null} to indicate that the property 1795 * <i>k</i> will not be added to the resulting configuration. 1796 * <br> 1797 * If {@code mapper} is {@code null} then {@code (k) -> ((o, n) -> n)} is 1798 * assumed. 1799 * <br> 1800 * For each <i>k</i>, the mapped function <i>f</i> will 1801 * be invoked with the value associated with <i>k</i> in the old 1802 * configuration (i.e <i>o</i>) and the value associated with 1803 * <i>k</i> in the new configuration (i.e. <i>n</i>). 1804 * <br>A {@code null} value for <i>o</i> or <i>n</i> indicates that no 1805 * value was present for <i>k</i> in the corresponding configuration. 1806 * 1807 * @throws SecurityException if a security manager exists and if 1808 * the caller does not have LoggingPermission("control"), or 1809 * does not have the permissions required to set up the 1810 * configuration (e.g. open file specified for FileHandlers 1811 * etc...) 1812 * 1813 * @throws NullPointerException if {@code mapper} returns a {@code null} 1814 * function when invoked. 1815 * 1816 * @throws IOException if there are problems reading from the 1817 * logging configuration file. 1818 * 1819 * @see #updateConfiguration(java.io.InputStream, java.util.function.Function) 1820 */ 1821 public void updateConfiguration(Function<String, BiFunction<String,String,String>> mapper) 1822 throws IOException { 1823 checkPermission(); 1824 ensureLogManagerInitialized(); 1825 drainLoggerRefQueueBounded(); 1826 1827 String fname = getConfigurationFileName(); 1828 try (final InputStream in = new FileInputStream(fname)) { 1829 final BufferedInputStream bin = new BufferedInputStream(in); 1830 updateConfiguration(bin, mapper); 1831 } 1832 } 1833 1834 /** 1835 * Updates the logging configuration. 1836 * <p> 1837 * For each configuration key in the {@linkplain 1838 * #getProperty(java.lang.String) existing configuration} and 1839 * the given input stream configuration, the given {@code mapper} function 1840 * is invoked to map from the configuration key to a function, 1841 * <i>f(o,n)</i>, that takes the old value and new value and returns 1842 * the resulting value to be applied in the resulting configuration, 1843 * as specified in the table below. 1844 * <p>Let <i>k</i> be a configuration key in the old or new configuration, 1845 * <i>o</i> be the old value (i.e. the value associated 1846 * with <i>k</i> in the old configuration), <i>n</i> be the 1847 * new value (i.e. the value associated with <i>k</i> in the new 1848 * configuration), and <i>f</i> be the function returned 1849 * by {@code mapper.apply(}<i>k</i>{@code )}: then <i>v = f(o,n)</i> is the 1850 * resulting value. If <i>v</i> is not {@code null}, then a property 1851 * <i>k</i> with value <i>v</i> will be added to the resulting configuration. 1852 * Otherwise, it will be omitted. 1853 * <br>A {@code null} value may be passed to function 1854 * <i>f</i> to indicate that the corresponding configuration has no 1855 * configuration key <i>k</i>. 1856 * The function <i>f</i> may return {@code null} to indicate that 1857 * there will be no value associated with <i>k</i> in the resulting 1858 * configuration. 1859 * <p> 1860 * If {@code mapper} is {@code null}, then <i>v</i> will be set to 1861 * <i>n</i>. 1862 * <p> 1863 * LogManager {@linkplain #getProperty(java.lang.String) properties} are 1864 * updated with the resulting value in the resulting configuration. 1865 * <p> 1866 * The registered {@linkplain #addConfigurationListener configuration 1867 * listeners} will be invoked after the configuration is successfully updated. 1868 * <br><br> 1869 * <table summary="Updating configuration properties"> 1870 * <tr> 1871 * <th>Property</th> 1872 * <th>Resulting Behavior</th> 1873 * </tr> 1874 * <tr> 1875 * <td valign="top">{@code <logger>.level}</td> 1876 * <td> 1877 * <ul> 1878 * <li>If the resulting configuration defines a level for a logger and 1879 * if the resulting level is different than the level specified in the 1880 * the old configuration, or not specified in 1881 * the old configuration, then if the logger exists or if children for 1882 * that logger exist, the level for that logger will be updated, 1883 * and the change propagated to any existing logger children. 1884 * This may cause the logger to be created, if necessary. 1885 * </li> 1886 * <li>If the old configuration defined a level for a logger, and the 1887 * resulting configuration doesn't, then this change will not be 1888 * propagated to existing loggers, if any. 1889 * To completely replace a configuration - the caller should therefore 1890 * call {@link #reset() reset} to empty the current configuration, 1891 * before calling {@code updateConfiguration}. 1892 * </li> 1893 * </ul> 1894 * </td> 1895 * <tr> 1896 * <td valign="top">{@code <logger>.useParentHandlers}</td> 1897 * <td> 1898 * <ul> 1899 * <li>If either the resulting or the old value for the useParentHandlers 1900 * property is not null, then if the logger exists or if children for 1901 * that logger exist, that logger will be updated to the resulting 1902 * value. 1903 * The value of the useParentHandlers property is the value specified 1904 * in the configuration; if not specified, the default is true. 1905 * </li> 1906 * </ul> 1907 * </td> 1908 * </tr> 1909 * <tr> 1910 * <td valign="top">{@code <logger>.handlers}</td> 1911 * <td> 1912 * <ul> 1913 * <li>If the resulting configuration defines a list of handlers for a 1914 * logger, and if the resulting list is different than the list 1915 * specified in the old configuration for that logger (that could be 1916 * empty), then if the logger exists or its children exist, the 1917 * handlers associated with that logger are closed and removed and 1918 * the new handlers will be created per the resulting configuration 1919 * and added to that logger, creating that logger if necessary. 1920 * </li> 1921 * <li>If the old configuration defined some handlers for a logger, and 1922 * the resulting configuration doesn't, if that logger exists, 1923 * its handlers will be removed and closed. 1924 * </li> 1925 * <li>Changing the list of handlers on an existing logger will cause all 1926 * its previous handlers to be removed and closed, regardless of whether 1927 * they had been created from the configuration or programmatically. 1928 * The old handlers will be replaced by new handlers, if any. 1929 * </li> 1930 * </ul> 1931 * </td> 1932 * </tr> 1933 * <tr> 1934 * <td valign="top">{@code <handler-name>.*}</td> 1935 * <td> 1936 * <ul> 1937 * <li>Properties configured/changed on handler classes will only affect 1938 * newly created handlers. If a node is configured with the same list 1939 * of handlers in the old and the resulting configuration, then these 1940 * handlers will remain unchanged. 1941 * </li> 1942 * </ul> 1943 * </td> 1944 * </tr> 1945 * <tr> 1946 * <td valign="top">{@code config} and any other property</td> 1947 * <td> 1948 * <ul> 1949 * <li>The resulting value for these property will be stored in the 1950 * LogManager properties, but {@code updateConfiguration} will not parse 1951 * or process their values. 1952 * </li> 1953 * </ul> 1954 * </td> 1955 * </tr> 1956 * </table> 1957 * <p> 1958 * <em>Example mapper functions:</em> 1959 * <br><br> 1960 * <ul> 1961 * <li>Replace all logging properties with the new configuration: 1962 * <br><br>{@code (k) -> ((o, n) -> n)}: 1963 * <br><br>this is equivalent to passing a null {@code mapper} parameter. 1964 * </li> 1965 * <li>Merge the new configuration and old configuration and use the 1966 * new value if <i>k</i> exists in the new configuration: 1967 * <br><br>{@code (k) -> ((o, n) -> n == null ? o : n)}: 1968 * <br><br>as if merging two collections as follows: 1969 * {@code result.putAll(oldc); result.putAll(newc)}.<br></li> 1970 * <li>Merge the new configuration and old configuration and use the old 1971 * value if <i>k</i> exists in the old configuration: 1972 * <br><br>{@code (k) -> ((o, n) -> o == null ? n : o)}: 1973 * <br><br>as if merging two collections as follows: 1974 * {@code result.putAll(newc); result.putAll(oldc)}.<br></li> 1975 * <li>Replace all properties with the new configuration except the handler 1976 * property to configure Logger's handler that is not root logger: 1977 * <br> 1978 * <pre>{@code (k) -> k.endsWith(".handlers")} 1979 * {@code ? ((o, n) -> (o == null ? n : o))} 1980 * {@code : ((o, n) -> n)}</pre> 1981 * </li> 1982 * </ul> 1983 * <p> 1984 * To completely reinitialize a configuration, an application can first call 1985 * {@link #reset() reset} to fully remove the old configuration, followed by 1986 * {@code updateConfiguration} to initialize the new configuration. 1987 * 1988 * @param ins a stream to read properties from 1989 * @param mapper a functional interface that takes a configuration 1990 * key <i>k</i> and returns a function <i>f(o,n)</i> whose returned 1991 * value will be applied to the resulting configuration. The 1992 * function <i>f</i> may return {@code null} to indicate that the property 1993 * <i>k</i> will not be added to the resulting configuration. 1994 * <br> 1995 * If {@code mapper} is {@code null} then {@code (k) -> ((o, n) -> n)} is 1996 * assumed. 1997 * <br> 1998 * For each <i>k</i>, the mapped function <i>f</i> will 1999 * be invoked with the value associated with <i>k</i> in the old 2000 * configuration (i.e <i>o</i>) and the value associated with 2001 * <i>k</i> in the new configuration (i.e. <i>n</i>). 2002 * <br>A {@code null} value for <i>o</i> or <i>n</i> indicates that no 2003 * value was present for <i>k</i> in the corresponding configuration. 2004 * 2005 * @throws SecurityException if a security manager exists and if 2006 * the caller does not have LoggingPermission("control"), or 2007 * does not have the permissions required to set up the 2008 * configuration (e.g. open files specified for FileHandlers) 2009 * 2010 * @throws NullPointerException if {@code ins} is null or if 2011 * {@code mapper} returns a null function when invoked. 2012 * 2013 * @throws IOException if there are problems reading from the stream, 2014 * or the given stream is not in the 2015 * {@linkplain java.util.Properties properties file} format. 2016 */ 2017 public void updateConfiguration(InputStream ins, 2018 Function<String, BiFunction<String,String,String>> mapper) 2019 throws IOException { 2020 checkPermission(); 2021 ensureLogManagerInitialized(); 2022 drainLoggerRefQueueBounded(); 2023 2024 final Properties previous; 2025 final Set<String> updatePropertyNames; 2026 List<LoggerContext> cxs = Collections.emptyList(); 2027 final VisitedLoggers visited = new VisitedLoggers(); 2028 final Properties next = new Properties(); 2029 2030 try { 2031 // Load the properties 2032 next.load(ins); 2033 } catch (IllegalArgumentException x) { 2034 // props.load may throw an IllegalArgumentException if the stream 2035 // contains malformed Unicode escape sequences. 2036 // We wrap that in an IOException as updateConfiguration is 2037 // specified to throw IOException if there are problems reading 2038 // from the stream. 2039 // Note: new IOException(x.getMessage(), x) allow us to get a more 2040 // concise error message than new IOException(x); 2041 throw new IOException(x.getMessage(), x); 2042 } 2043 2044 if (globalHandlersState == STATE_SHUTDOWN) return; 2045 2046 // exclusive lock: readConfiguration/reset/updateConfiguration can't 2047 // run concurrently. 2048 // configurationLock.writeLock().lock(); 2049 configurationLock.lock(); 2050 try { 2051 if (globalHandlersState == STATE_SHUTDOWN) return; 2052 previous = props; 2053 2054 // Builds a TreeSet of all (old and new) property names. 2055 updatePropertyNames = 2056 Stream.concat(previous.stringPropertyNames().stream(), 2057 next.stringPropertyNames().stream()) 2058 .collect(Collectors.toCollection(TreeSet::new)); 2059 2060 if (mapper != null) { 2061 // mapper will potentially modify the content of 2062 // 'next', so we need to call it before affecting props=next. 2063 // give a chance to the mapper to control all 2064 // properties - not just those we will reset. 2065 updatePropertyNames.stream() 2066 .forEachOrdered(k -> ConfigProperty 2067 .merge(k, previous, next, 2068 Objects.requireNonNull(mapper.apply(k)))); 2069 } 2070 2071 props = next; 2072 2073 // allKeys will contain all keys: 2074 // - which correspond to a configuration property we are interested in 2075 // (first filter) 2076 // - whose value needs to be updated (because it's new, removed, or 2077 // different) in the resulting configuration (second filter) 2078 final Stream<String> allKeys = updatePropertyNames.stream() 2079 .filter(ConfigProperty::matches) 2080 .filter(k -> ConfigProperty.needsUpdating(k, previous, next)); 2081 2082 // Group configuration properties by logger name 2083 // We use a TreeMap so that parent loggers will be visited before 2084 // child loggers. 2085 final Map<String, TreeSet<String>> loggerConfigs = 2086 allKeys.collect(Collectors.groupingBy(ConfigProperty::getLoggerName, 2087 TreeMap::new, 2088 Collectors.toCollection(TreeSet::new))); 2089 2090 if (!loggerConfigs.isEmpty()) { 2091 cxs = contexts(); 2092 } 2093 final List<Logger> loggers = cxs.isEmpty() 2094 ? Collections.emptyList() : new ArrayList<>(cxs.size()); 2095 for (Map.Entry<String, TreeSet<String>> e : loggerConfigs.entrySet()) { 2096 // This can be a logger name, or something else... 2097 // The only thing we know is that we found a property 2098 // we are interested in. 2099 // For instance, if we found x.y.z.level, then x.y.z could be 2100 // a logger, but it could also be a handler class... 2101 // Anyway... 2102 final String name = e.getKey(); 2103 final Set<String> properties = e.getValue(); 2104 loggers.clear(); 2105 for (LoggerContext cx : cxs) { 2106 Logger l = cx.findLogger(name); 2107 if (l != null && !visited.test(l)) { 2108 loggers.add(l); 2109 } 2110 } 2111 if (loggers.isEmpty()) continue; 2112 for (String pk : properties) { 2113 ConfigProperty cp = ConfigProperty.find(pk).get(); 2114 String p = previous.getProperty(pk, null); 2115 String n = next.getProperty(pk, null); 2116 2117 // Determines the type of modification. 2118 ModType mod = ModType.of(p, n); 2119 2120 // mod == SAME means that the two values are equals, there 2121 // is nothing to do. Usually, this should not happen as such 2122 // properties should have been filtered above. 2123 // It could happen however if the properties had 2124 // trailing/leading whitespaces. 2125 if (mod == ModType.SAME) continue; 2126 2127 switch (cp) { 2128 case LEVEL: 2129 if (mod == ModType.REMOVED) continue; 2130 Level level = Level.findLevel(trim(n)); 2131 if (level != null) { 2132 if (name.isEmpty()) { 2133 rootLogger.setLevel(level); 2134 } 2135 for (Logger l : loggers) { 2136 if (!name.isEmpty() || l != rootLogger) { 2137 l.setLevel(level); 2138 } 2139 } 2140 } 2141 break; 2142 case USEPARENT: 2143 if (!name.isEmpty()) { 2144 boolean useParent = getBooleanProperty(pk, true); 2145 if (n != null || p != null) { 2146 // reset the flag only if the previous value 2147 // or the new value are not null. 2148 for (Logger l : loggers) { 2149 l.setUseParentHandlers(useParent); 2150 } 2151 } 2152 } 2153 break; 2154 case HANDLERS: 2155 List<Handler> hdls = null; 2156 if (name.isEmpty()) { 2157 // special handling for the root logger. 2158 globalHandlersState = STATE_READING_CONFIG; 2159 try { 2160 closeHandlers(rootLogger); 2161 globalHandlersState = STATE_UNINITIALIZED; 2162 } catch (Throwable t) { 2163 globalHandlersState = STATE_INITIALIZED; 2164 throw t; 2165 } 2166 } 2167 for (Logger l : loggers) { 2168 if (l == rootLogger) continue; 2169 closeHandlers(l); 2170 if (mod == ModType.REMOVED) { 2171 closeOnResetLoggers.removeIf(c -> c.logger == l); 2172 continue; 2173 } 2174 if (hdls == null) { 2175 hdls = name.isEmpty() 2176 ? Arrays.asList(rootLogger.getHandlers()) 2177 : createLoggerHandlers(name, pk); 2178 } 2179 setLoggerHandlers(l, name, pk, hdls); 2180 } 2181 break; 2182 default: break; 2183 } 2184 } 2185 } 2186 } finally { 2187 configurationLock.unlock(); 2188 visited.clear(); 2189 } 2190 2191 // Now ensure that if an existing logger has acquired a new parent 2192 // in the configuration, this new parent will be created - if needed, 2193 // and added to the context of the existing child. 2194 // 2195 drainLoggerRefQueueBounded(); 2196 for (LoggerContext cx : cxs) { 2197 for (Enumeration<String> names = cx.getLoggerNames() ; names.hasMoreElements();) { 2198 String name = names.nextElement(); 2199 if (name.isEmpty()) continue; // don't need to process parents on root. 2200 Logger l = cx.findLogger(name); 2201 if (l != null && !visited.test(l)) { 2202 // should pass visited here to cut the processing when 2203 // reaching a logger already visited. 2204 cx.processParentHandlers(l, name, visited); 2205 } 2206 } 2207 } 2208 2209 // We changed the configuration: invoke configuration listeners 2210 invokeConfigurationListeners(); 2211 } 2212 2213 /** 2214 * Get the value of a logging property. 2215 * The method returns null if the property is not found. 2216 * @param name property name 2217 * @return property value 2218 */ 2219 public String getProperty(String name) { 2220 return props.getProperty(name); 2221 } 2222 2223 // Package private method to get a String property. 2224 // If the property is not defined we return the given 2225 // default value. 2226 String getStringProperty(String name, String defaultValue) { 2227 String val = getProperty(name); 2228 if (val == null) { 2229 return defaultValue; 2230 } 2231 return val.trim(); 2232 } 2233 2234 // Package private method to get an integer property. 2235 // If the property is not defined or cannot be parsed 2236 // we return the given default value. 2237 int getIntProperty(String name, int defaultValue) { 2238 String val = getProperty(name); 2239 if (val == null) { 2240 return defaultValue; 2241 } 2242 try { 2243 return Integer.parseInt(val.trim()); 2244 } catch (Exception ex) { 2245 return defaultValue; 2246 } 2247 } 2248 2249 // Package private method to get a long property. 2250 // If the property is not defined or cannot be parsed 2251 // we return the given default value. 2252 long getLongProperty(String name, long defaultValue) { 2253 String val = getProperty(name); 2254 if (val == null) { 2255 return defaultValue; 2256 } 2257 try { 2258 return Long.parseLong(val.trim()); 2259 } catch (Exception ex) { 2260 return defaultValue; 2261 } 2262 } 2263 2264 // Package private method to get a boolean property. 2265 // If the property is not defined or cannot be parsed 2266 // we return the given default value. 2267 boolean getBooleanProperty(String name, boolean defaultValue) { 2268 String val = getProperty(name); 2269 if (val == null) { 2270 return defaultValue; 2271 } 2272 val = val.toLowerCase(); 2273 if (val.equals("true") || val.equals("1")) { 2274 return true; 2275 } else if (val.equals("false") || val.equals("0")) { 2276 return false; 2277 } 2278 return defaultValue; 2279 } 2280 2281 // Package private method to get a Level property. 2282 // If the property is not defined or cannot be parsed 2283 // we return the given default value. 2284 Level getLevelProperty(String name, Level defaultValue) { 2285 String val = getProperty(name); 2286 if (val == null) { 2287 return defaultValue; 2288 } 2289 Level l = Level.findLevel(val.trim()); 2290 return l != null ? l : defaultValue; 2291 } 2292 2293 // Package private method to get a filter property. 2294 // We return an instance of the class named by the "name" 2295 // property. If the property is not defined or has problems 2296 // we return the defaultValue. 2297 Filter getFilterProperty(String name, Filter defaultValue) { 2298 String val = getProperty(name); 2299 try { 2300 if (val != null) { 2301 @SuppressWarnings("deprecation") 2302 Object o = ClassLoader.getSystemClassLoader().loadClass(val).newInstance(); 2303 return (Filter) o; 2304 } 2305 } catch (Exception ex) { 2306 // We got one of a variety of exceptions in creating the 2307 // class or creating an instance. 2308 // Drop through. 2309 } 2310 // We got an exception. Return the defaultValue. 2311 return defaultValue; 2312 } 2313 2314 2315 // Package private method to get a formatter property. 2316 // We return an instance of the class named by the "name" 2317 // property. If the property is not defined or has problems 2318 // we return the defaultValue. 2319 Formatter getFormatterProperty(String name, Formatter defaultValue) { 2320 String val = getProperty(name); 2321 try { 2322 if (val != null) { 2323 @SuppressWarnings("deprecation") 2324 Object o = ClassLoader.getSystemClassLoader().loadClass(val).newInstance(); 2325 return (Formatter) o; 2326 } 2327 } catch (Exception ex) { 2328 // We got one of a variety of exceptions in creating the 2329 // class or creating an instance. 2330 // Drop through. 2331 } 2332 // We got an exception. Return the defaultValue. 2333 return defaultValue; 2334 } 2335 2336 // Private method to load the global handlers. 2337 // We do the real work lazily, when the global handlers 2338 // are first used. 2339 private void initializeGlobalHandlers() { 2340 int state = globalHandlersState; 2341 if (state == STATE_INITIALIZED || 2342 state == STATE_SHUTDOWN) { 2343 // Nothing to do: return. 2344 return; 2345 } 2346 2347 // If we have not initialized global handlers yet (or need to 2348 // reinitialize them), lets do it now (this case is indicated by 2349 // globalHandlersState == STATE_UNINITIALIZED). 2350 // If we are in the process of initializing global handlers we 2351 // also need to lock & wait (this case is indicated by 2352 // globalHandlersState == STATE_INITIALIZING). 2353 // If we are in the process of reading configuration we also need to 2354 // wait to see what the outcome will be (this case 2355 // is indicated by globalHandlersState == STATE_READING_CONFIG) 2356 // So in either case we need to wait for the lock. 2357 configurationLock.lock(); 2358 try { 2359 if (globalHandlersState != STATE_UNINITIALIZED) { 2360 return; // recursive call or nothing to do 2361 } 2362 // set globalHandlersState to STATE_INITIALIZING first to avoid 2363 // getting an infinite recursion when loadLoggerHandlers(...) 2364 // is going to call addHandler(...) 2365 globalHandlersState = STATE_INITIALIZING; 2366 try { 2367 loadLoggerHandlers(rootLogger, null, "handlers"); 2368 } finally { 2369 globalHandlersState = STATE_INITIALIZED; 2370 } 2371 } finally { 2372 configurationLock.unlock(); 2373 } 2374 } 2375 2376 static final Permission controlPermission = 2377 new LoggingPermission("control", null); 2378 2379 void checkPermission() { 2380 SecurityManager sm = System.getSecurityManager(); 2381 if (sm != null) 2382 sm.checkPermission(controlPermission); 2383 } 2384 2385 /** 2386 * Check that the current context is trusted to modify the logging 2387 * configuration. This requires LoggingPermission("control"). 2388 * <p> 2389 * If the check fails we throw a SecurityException, otherwise 2390 * we return normally. 2391 * 2392 * @exception SecurityException if a security manager exists and if 2393 * the caller does not have LoggingPermission("control"). 2394 */ 2395 public void checkAccess() throws SecurityException { 2396 checkPermission(); 2397 } 2398 2399 // Nested class to represent a node in our tree of named loggers. 2400 private static class LogNode { 2401 HashMap<String,LogNode> children; 2402 LoggerWeakRef loggerRef; 2403 LogNode parent; 2404 final LoggerContext context; 2405 2406 LogNode(LogNode parent, LoggerContext context) { 2407 this.parent = parent; 2408 this.context = context; 2409 } 2410 2411 // Recursive method to walk the tree below a node and set 2412 // a new parent logger. 2413 void walkAndSetParent(Logger parent) { 2414 if (children == null) { 2415 return; 2416 } 2417 for (LogNode node : children.values()) { 2418 LoggerWeakRef ref = node.loggerRef; 2419 Logger logger = (ref == null) ? null : ref.get(); 2420 if (logger == null) { 2421 node.walkAndSetParent(parent); 2422 } else { 2423 doSetParent(logger, parent); 2424 } 2425 } 2426 } 2427 } 2428 2429 // We use a subclass of Logger for the root logger, so 2430 // that we only instantiate the global handlers when they 2431 // are first needed. 2432 private final class RootLogger extends Logger { 2433 private RootLogger() { 2434 // We do not call the protected Logger two args constructor here, 2435 // to avoid calling LogManager.getLogManager() from within the 2436 // RootLogger constructor. 2437 super("", null, null, LogManager.this, true); 2438 } 2439 2440 @Override 2441 public void log(LogRecord record) { 2442 // Make sure that the global handlers have been instantiated. 2443 initializeGlobalHandlers(); 2444 super.log(record); 2445 } 2446 2447 @Override 2448 public void addHandler(Handler h) { 2449 initializeGlobalHandlers(); 2450 super.addHandler(h); 2451 } 2452 2453 @Override 2454 public void removeHandler(Handler h) { 2455 initializeGlobalHandlers(); 2456 super.removeHandler(h); 2457 } 2458 2459 @Override 2460 Handler[] accessCheckedHandlers() { 2461 initializeGlobalHandlers(); 2462 return super.accessCheckedHandlers(); 2463 } 2464 } 2465 2466 2467 // Private method to be called when the configuration has 2468 // changed to apply any level settings to any pre-existing loggers. 2469 private void setLevelsOnExistingLoggers() { 2470 Enumeration<?> enum_ = props.propertyNames(); 2471 while (enum_.hasMoreElements()) { 2472 String key = (String)enum_.nextElement(); 2473 if (!key.endsWith(".level")) { 2474 // Not a level definition. 2475 continue; 2476 } 2477 int ix = key.length() - 6; 2478 String name = key.substring(0, ix); 2479 Level level = getLevelProperty(key, null); 2480 if (level == null) { 2481 System.err.println("Bad level value for property: " + key); 2482 continue; 2483 } 2484 for (LoggerContext cx : contexts()) { 2485 Logger l = cx.findLogger(name); 2486 if (l == null) { 2487 continue; 2488 } 2489 l.setLevel(level); 2490 } 2491 } 2492 } 2493 2494 // Management Support 2495 private static LoggingMXBean loggingMXBean = null; 2496 /** 2497 * String representation of the 2498 * {@link javax.management.ObjectName} for the management interface 2499 * for the logging facility. 2500 * 2501 * @see java.lang.management.PlatformLoggingMXBean 2502 * @see java.util.logging.LoggingMXBean 2503 * 2504 * @since 1.5 2505 */ 2506 public final static String LOGGING_MXBEAN_NAME 2507 = "java.util.logging:type=Logging"; 2508 2509 /** 2510 * Returns {@code LoggingMXBean} for managing loggers. 2511 * An alternative way to manage loggers is through the 2512 * {@link java.lang.management.PlatformLoggingMXBean} interface 2513 * that can be obtained by calling: 2514 * <pre> 2515 * PlatformLoggingMXBean logging = {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class) 2516 * ManagementFactory.getPlatformMXBean}(PlatformLoggingMXBean.class); 2517 * </pre> 2518 * 2519 * @return a {@link LoggingMXBean} object. 2520 * 2521 * @see java.lang.management.PlatformLoggingMXBean 2522 * @since 1.5 2523 */ 2524 public static synchronized LoggingMXBean getLoggingMXBean() { 2525 if (loggingMXBean == null) { 2526 loggingMXBean = new Logging(); 2527 } 2528 return loggingMXBean; 2529 } 2530 2531 /** 2532 * Adds a configuration listener to be invoked each time the logging 2533 * configuration is read. 2534 * If the listener is already registered the method does nothing. 2535 * <p> 2536 * The listener is invoked with privileges that are restricted by the 2537 * calling context of this method. 2538 * The order in which the listeners are invoked is unspecified. 2539 * <p> 2540 * It is recommended that listeners do not throw errors or exceptions. 2541 * 2542 * If a listener terminates with an uncaught error or exception then 2543 * the first exception will be propagated to the caller of 2544 * {@link #readConfiguration()} (or {@link #readConfiguration(java.io.InputStream)}) 2545 * after all listeners have been invoked. 2546 * 2547 * @implNote If more than one listener terminates with an uncaught error or 2548 * exception, an implementation may record the additional errors or 2549 * exceptions as {@linkplain Throwable#addSuppressed(java.lang.Throwable) 2550 * suppressed exceptions}. 2551 * 2552 * @param listener A configuration listener that will be invoked after the 2553 * configuration changed. 2554 * @return This LogManager. 2555 * @throws SecurityException if a security manager exists and if the 2556 * caller does not have LoggingPermission("control"). 2557 * @throws NullPointerException if the listener is null. 2558 * 2559 * @since 9 2560 */ 2561 public LogManager addConfigurationListener(Runnable listener) { 2562 final Runnable r = Objects.requireNonNull(listener); 2563 checkPermission(); 2564 final SecurityManager sm = System.getSecurityManager(); 2565 final AccessControlContext acc = 2566 sm == null ? null : AccessController.getContext(); 2567 final PrivilegedAction<Void> pa = 2568 acc == null ? null : () -> { r.run() ; return null; }; 2569 final Runnable pr = 2570 acc == null ? r : () -> AccessController.doPrivileged(pa, acc); 2571 // Will do nothing if already registered. 2572 listeners.putIfAbsent(r, pr); 2573 return this; 2574 } 2575 2576 /** 2577 * Removes a previously registered configuration listener. 2578 * 2579 * Returns silently if the listener is not found. 2580 * 2581 * @param listener the configuration listener to remove. 2582 * @throws NullPointerException if the listener is null. 2583 * @throws SecurityException if a security manager exists and if the 2584 * caller does not have LoggingPermission("control"). 2585 * 2586 * @since 9 2587 */ 2588 public void removeConfigurationListener(Runnable listener) { 2589 final Runnable key = Objects.requireNonNull(listener); 2590 checkPermission(); 2591 listeners.remove(key); 2592 } 2593 2594 private void invokeConfigurationListeners() { 2595 Throwable t = null; 2596 2597 // We're using an IdentityHashMap because we want to compare 2598 // keys using identity (==). 2599 // We don't want to loop within a block synchronized on 'listeners' 2600 // to avoid invoking listeners from yet another synchronized block. 2601 // So we're taking a snapshot of the values list to avoid the risk of 2602 // ConcurrentModificationException while looping. 2603 // 2604 for (Runnable c : listeners.values().toArray(new Runnable[0])) { 2605 try { 2606 c.run(); 2607 } catch (ThreadDeath death) { 2608 throw death; 2609 } catch (Error | RuntimeException x) { 2610 if (t == null) t = x; 2611 else t.addSuppressed(x); 2612 } 2613 } 2614 // Listeners are not supposed to throw exceptions, but if that 2615 // happens, we will rethrow the first error or exception that is raised 2616 // after all listeners have been invoked. 2617 if (t instanceof Error) throw (Error)t; 2618 if (t instanceof RuntimeException) throw (RuntimeException)t; 2619 } 2620 2621 /** 2622 * This class allows the {@link LoggingProviderImpl} to demand loggers on 2623 * behalf of system and application classes. 2624 */ 2625 private static final class LoggingProviderAccess 2626 implements LoggingProviderImpl.LogManagerAccess, 2627 PrivilegedAction<Void> { 2628 2629 private LoggingProviderAccess() { 2630 } 2631 2632 /** 2633 * Demands a logger on behalf of the given {@code caller}. 2634 * <p> 2635 * If a named logger suitable for the given caller is found 2636 * returns it. 2637 * Otherwise, creates a new logger suitable for the given caller. 2638 * 2639 * @param name The logger name. 2640 * @param caller The caller on which behalf the logger is created/retrieved. 2641 * @return A logger for the given {@code caller}. 2642 * 2643 * @throws NullPointerException if {@code name} is {@code null} 2644 * or {@code caller} is {@code null}. 2645 * @throws IllegalArgumentException if {@code manager} is not the default 2646 * LogManager. 2647 * @throws SecurityException if a security manager is present and the 2648 * calling code doesn't have the 2649 * {@link LoggingPermission LoggingPermission("demandLogger", null)}. 2650 */ 2651 @Override 2652 public Logger demandLoggerFor(LogManager manager, String name, /* Module */ Class<?> caller) { 2653 if (manager != getLogManager()) { 2654 // having LogManager as parameter just ensures that the 2655 // caller will have initialized the LogManager before reaching 2656 // here. 2657 throw new IllegalArgumentException("manager"); 2658 } 2659 Objects.requireNonNull(name); 2660 SecurityManager sm = System.getSecurityManager(); 2661 if (sm != null) { 2662 sm.checkPermission(controlPermission); 2663 } 2664 if (caller.getClassLoader() == null) { 2665 return manager.demandSystemLogger(name, 2666 Logger.SYSTEM_LOGGER_RB_NAME, caller); 2667 } else { 2668 return manager.demandLogger(name, null, caller); 2669 } 2670 } 2671 2672 @Override 2673 public Void run() { 2674 LoggingProviderImpl.setLogManagerAccess(INSTANCE); 2675 return null; 2676 } 2677 2678 static final LoggingProviderAccess INSTANCE = new LoggingProviderAccess(); 2679 } 2680 2681 static { 2682 AccessController.doPrivileged(LoggingProviderAccess.INSTANCE, null, 2683 controlPermission); 2684 } 2685 2686 }