1 /* 2 * Copyright (c) 2000, 2013, 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.lang.reflect.Constructor; 35 import java.lang.reflect.InvocationTargetException; 36 import java.lang.reflect.Method; 37 import java.beans.PropertyChangeListener; 38 import sun.misc.JavaAWTAccess; 39 import sun.misc.SharedSecrets; 40 41 /** 42 * There is a single global LogManager object that is used to 43 * maintain a set of shared state about Loggers and log services. 44 * <p> 45 * This LogManager object: 46 * <ul> 47 * <li> Manages a hierarchical namespace of Logger objects. All 48 * named Loggers are stored in this namespace. 49 * <li> Manages a set of logging control properties. These are 50 * simple key-value pairs that can be used by Handlers and 51 * other logging objects to configure themselves. 52 * </ul> 53 * <p> 54 * The global LogManager object can be retrieved using LogManager.getLogManager(). 55 * The LogManager object is created during class initialization and 56 * cannot subsequently be changed. 57 * <p> 58 * At startup the LogManager class is located using the 59 * java.util.logging.manager system property. 60 * <p> 61 * The LogManager defines two optional system properties that allow control over 62 * the initial configuration: 63 * <ul> 64 * <li>"java.util.logging.config.class" 65 * <li>"java.util.logging.config.file" 66 * </ul> 67 * These two properties may be specified on the command line to the "java" 68 * command, or as system property definitions passed to JNI_CreateJavaVM. 69 * <p> 70 * If the "java.util.logging.config.class" property is set, then the 71 * property value is treated as a class name. The given class will be 72 * loaded, an object will be instantiated, and that object's constructor 73 * is responsible for reading in the initial configuration. (That object 74 * may use other system properties to control its configuration.) The 75 * alternate configuration class can use <tt>readConfiguration(InputStream)</tt> 76 * to define properties in the LogManager. 77 * <p> 78 * If "java.util.logging.config.class" property is <b>not</b> set, 79 * then the "java.util.logging.config.file" system property can be used 80 * to specify a properties file (in java.util.Properties format). The 81 * initial logging configuration will be read from this file. 82 * <p> 83 * If neither of these properties is defined then the LogManager uses its 84 * default configuration. The default configuration is typically loaded from the 85 * properties file "{@code lib/logging.properties}" in the Java installation 86 * directory. 87 * <p> 88 * The properties for loggers and Handlers will have names starting 89 * with the dot-separated name for the handler or logger. 90 * <p> 91 * The global logging properties may include: 92 * <ul> 93 * <li>A property "handlers". This defines a whitespace or comma separated 94 * list of class names for handler classes to load and register as 95 * handlers on the root Logger (the Logger named ""). Each class 96 * name must be for a Handler class which has a default constructor. 97 * Note that these Handlers may be created lazily, when they are 98 * first used. 99 * 100 * <li>A property "<logger>.handlers". This defines a whitespace or 101 * comma separated list of class names for handlers classes to 102 * load and register as handlers to the specified logger. Each class 103 * name must be for a Handler class which has a default constructor. 104 * Note that these Handlers may be created lazily, when they are 105 * first used. 106 * 107 * <li>A property "<logger>.useParentHandlers". This defines a boolean 108 * value. By default every logger calls its parent in addition to 109 * handling the logging message itself, this often result in messages 110 * being handled by the root logger as well. When setting this property 111 * to false a Handler needs to be configured for this logger otherwise 112 * no logging messages are delivered. 113 * 114 * <li>A property "config". This property is intended to allow 115 * arbitrary configuration code to be run. The property defines a 116 * whitespace or comma separated list of class names. A new instance will be 117 * created for each named class. The default constructor of each class 118 * may execute arbitrary code to update the logging configuration, such as 119 * setting logger levels, adding handlers, adding filters, etc. 120 * </ul> 121 * <p> 122 * Note that all classes loaded during LogManager configuration are 123 * first searched on the system class path before any user class path. 124 * That includes the LogManager class, any config classes, and any 125 * handler classes. 126 * <p> 127 * Loggers are organized into a naming hierarchy based on their 128 * dot separated names. Thus "a.b.c" is a child of "a.b", but 129 * "a.b1" and a.b2" are peers. 130 * <p> 131 * All properties whose names end with ".level" are assumed to define 132 * log levels for Loggers. Thus "foo.level" defines a log level for 133 * the logger called "foo" and (recursively) for any of its children 134 * in the naming hierarchy. Log Levels are applied in the order they 135 * are defined in the properties file. Thus level settings for child 136 * nodes in the tree should come after settings for their parents. 137 * The property name ".level" can be used to set the level for the 138 * root of the tree. 139 * <p> 140 * All methods on the LogManager object are multi-thread safe. 141 * 142 * @since 1.4 143 */ 144 145 public class LogManager { 146 // The global LogManager object 147 private static LogManager manager; 148 149 private Properties props = new Properties(); 150 private final static Level defaultLevel = Level.INFO; 151 152 // The map of the registered listeners. The map value is the registration 153 // count to allow for cases where the same listener is registered many times. 154 private final Map<Object,Integer> listenerMap = new HashMap<>(); 155 156 // LoggerContext for system loggers and user loggers 157 private final LoggerContext systemContext = new SystemLoggerContext(); 158 private final LoggerContext userContext = new LoggerContext(); 159 private Logger rootLogger; 160 161 // Have we done the primordial reading of the configuration file? 162 // (Must be done after a suitable amount of java.lang.System 163 // initialization has been done) 164 private volatile boolean readPrimordialConfiguration; 165 // Have we initialized global (root) handlers yet? 166 // This gets set to false in readConfiguration 167 private boolean initializedGlobalHandlers = true; 168 // True if JVM death is imminent and the exit hook has been called. 169 private boolean deathImminent; 170 171 static { 172 AccessController.doPrivileged(new PrivilegedAction<Object>() { 173 public Object run() { 174 String cname = null; 175 try { 176 cname = System.getProperty("java.util.logging.manager"); 177 if (cname != null) { 178 try { 179 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(cname); 180 manager = (LogManager) clz.newInstance(); 181 } catch (ClassNotFoundException ex) { 182 Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(cname); 183 manager = (LogManager) clz.newInstance(); 184 } 185 } 186 } catch (Exception ex) { 187 System.err.println("Could not load Logmanager \"" + cname + "\""); 188 ex.printStackTrace(); 189 } 190 if (manager == null) { 191 manager = new LogManager(); 192 } 193 194 // Create and retain Logger for the root of the namespace. 195 manager.rootLogger = manager.new RootLogger(); 196 // since by design the global manager's userContext and 197 // systemContext don't have their requiresDefaultLoggers 198 // flag set - we make sure to add the root logger to 199 // the global manager's default contexts here. 200 manager.addLogger(manager.rootLogger); 201 manager.systemContext.addLocalLogger(manager.rootLogger, false); 202 manager.userContext.addLocalLogger(manager.rootLogger, false); 203 204 // Adding the global Logger. Doing so in the Logger.<clinit> 205 // would deadlock with the LogManager.<clinit>. 206 // Do not call Logger.getGlobal() here as this might trigger 207 // the deadlock too. 208 @SuppressWarnings("deprecation") 209 final Logger global = Logger.global; 210 global.setLogManager(manager); 211 212 // Make sure the global logger will be registered in the 213 // global manager's default contexts. 214 manager.addLogger(global); 215 manager.systemContext.addLocalLogger(global, false); 216 manager.userContext.addLocalLogger(global, false); 217 218 // We don't call readConfiguration() here, as we may be running 219 // very early in the JVM startup sequence. Instead readConfiguration 220 // will be called lazily in getLogManager(). 221 return null; 222 } 223 }); 224 } 225 226 227 // This private class is used as a shutdown hook. 228 // It does a "reset" to close all open handlers. 229 private class Cleaner extends Thread { 230 231 private Cleaner() { 232 /* Set context class loader to null in order to avoid 233 * keeping a strong reference to an application classloader. 234 */ 235 this.setContextClassLoader(null); 236 } 237 238 public void run() { 239 // This is to ensure the LogManager.<clinit> is completed 240 // before synchronized block. Otherwise deadlocks are possible. 241 LogManager mgr = manager; 242 243 // If the global handlers haven't been initialized yet, we 244 // don't want to initialize them just so we can close them! 245 synchronized (LogManager.this) { 246 // Note that death is imminent. 247 deathImminent = true; 248 initializedGlobalHandlers = true; 249 } 250 251 // Do a reset to close all active handlers. 252 reset(); 253 } 254 } 255 256 257 /** 258 * Protected constructor. This is protected so that container applications 259 * (such as J2EE containers) can subclass the object. It is non-public as 260 * it is intended that there only be one LogManager object, whose value is 261 * retrieved by calling LogManager.getLogManager. 262 */ 263 protected LogManager() { 264 // Add a shutdown hook to close the global handlers. 265 try { 266 Runtime.getRuntime().addShutdownHook(new Cleaner()); 267 } catch (IllegalStateException e) { 268 // If the VM is already shutting down, 269 // We do not need to register shutdownHook. 270 } 271 } 272 273 /** 274 * Returns the global LogManager object. 275 * @return the global LogManager object 276 */ 277 public static LogManager getLogManager() { 278 if (manager != null) { 279 manager.readPrimordialConfiguration(); 280 } 281 return manager; 282 } 283 284 private void readPrimordialConfiguration() { 285 if (!readPrimordialConfiguration) { 286 synchronized (this) { 287 if (!readPrimordialConfiguration) { 288 // If System.in/out/err are null, it's a good 289 // indication that we're still in the 290 // bootstrapping phase 291 if (System.out == null) { 292 return; 293 } 294 readPrimordialConfiguration = true; 295 296 try { 297 AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() { 298 public Void run() throws Exception { 299 readConfiguration(); 300 301 // Platform loggers begin to delegate to java.util.logging.Logger 302 sun.util.logging.PlatformLogger.redirectPlatformLoggers(); 303 return null; 304 } 305 }); 306 } catch (Exception ex) { 307 // System.err.println("Can't read logging configuration:"); 308 // ex.printStackTrace(); 309 } 310 } 311 } 312 } 313 } 314 315 /** 316 * Adds an event listener to be invoked when the logging 317 * properties are re-read. Adding multiple instances of 318 * the same event Listener results in multiple entries 319 * in the property event listener table. 320 * 321 * <p><b>WARNING:</b> This method is omitted from this class in all subset 322 * Profiles of Java SE that do not include the {@code java.beans} package. 323 * </p> 324 * 325 * @param l event listener 326 * @exception SecurityException if a security manager exists and if 327 * the caller does not have LoggingPermission("control"). 328 * @exception NullPointerException if the PropertyChangeListener is null. 329 * @deprecated The dependency on {@code PropertyChangeListener} creates a 330 * significant impediment to future modularization of the Java 331 * platform. This method will be removed in a future release. 332 * The global {@code LogManager} can detect changes to the 333 * logging configuration by overridding the {@link 334 * #readConfiguration readConfiguration} method. 335 */ 336 @Deprecated 337 public void addPropertyChangeListener(PropertyChangeListener l) throws SecurityException { 338 PropertyChangeListener listener = Objects.requireNonNull(l); 339 checkPermission(); 340 synchronized (listenerMap) { 341 // increment the registration count if already registered 342 Integer value = listenerMap.get(listener); 343 value = (value == null) ? 1 : (value + 1); 344 listenerMap.put(listener, value); 345 } 346 } 347 348 /** 349 * Removes an event listener for property change events. 350 * If the same listener instance has been added to the listener table 351 * through multiple invocations of <CODE>addPropertyChangeListener</CODE>, 352 * then an equivalent number of 353 * <CODE>removePropertyChangeListener</CODE> invocations are required to remove 354 * all instances of that listener from the listener table. 355 * <P> 356 * Returns silently if the given listener is not found. 357 * 358 * <p><b>WARNING:</b> This method is omitted from this class in all subset 359 * Profiles of Java SE that do not include the {@code java.beans} package. 360 * </p> 361 * 362 * @param l event listener (can be null) 363 * @exception SecurityException if a security manager exists and if 364 * the caller does not have LoggingPermission("control"). 365 * @deprecated The dependency on {@code PropertyChangeListener} creates a 366 * significant impediment to future modularization of the Java 367 * platform. This method will be removed in a future release. 368 * The global {@code LogManager} can detect changes to the 369 * logging configuration by overridding the {@link 370 * #readConfiguration readConfiguration} method. 371 */ 372 @Deprecated 373 public void removePropertyChangeListener(PropertyChangeListener l) throws SecurityException { 374 checkPermission(); 375 if (l != null) { 376 PropertyChangeListener listener = l; 377 synchronized (listenerMap) { 378 Integer value = listenerMap.get(listener); 379 if (value != null) { 380 // remove from map if registration count is 1, otherwise 381 // just decrement its count 382 int i = value.intValue(); 383 if (i == 1) { 384 listenerMap.remove(listener); 385 } else { 386 assert i > 1; 387 listenerMap.put(listener, i - 1); 388 } 389 } 390 } 391 } 392 } 393 394 // LoggerContext maps from AppContext 395 private static WeakHashMap<Object, LoggerContext> contextsMap = null; 396 397 // Returns the LoggerContext for the user code (i.e. application or AppContext). 398 // Loggers are isolated from each AppContext. 399 private LoggerContext getUserContext() { 400 LoggerContext context = null; 401 402 SecurityManager sm = System.getSecurityManager(); 403 JavaAWTAccess javaAwtAccess = SharedSecrets.getJavaAWTAccess(); 404 if (sm != null && javaAwtAccess != null) { 405 // for each applet, it has its own LoggerContext isolated from others 406 synchronized (javaAwtAccess) { 407 // find the AppContext of the applet code 408 // will be null if we are in the main app context. 409 final Object ecx = javaAwtAccess.getAppletContext(); 410 if (ecx != null) { 411 if (contextsMap == null) { 412 contextsMap = new WeakHashMap<>(); 413 } 414 context = contextsMap.get(ecx); 415 if (context == null) { 416 // Create a new LoggerContext for the applet. 417 // The new logger context has its requiresDefaultLoggers 418 // flag set to true - so that these loggers will be 419 // lazily added when the context is firt accessed. 420 context = new LoggerContext(true); 421 contextsMap.put(ecx, context); 422 } 423 } 424 } 425 } 426 // for standalone app, return userContext 427 return context != null ? context : userContext; 428 } 429 430 private List<LoggerContext> contexts() { 431 List<LoggerContext> cxs = new ArrayList<>(); 432 cxs.add(systemContext); 433 cxs.add(getUserContext()); 434 return cxs; 435 } 436 437 // Find or create a specified logger instance. If a logger has 438 // already been created with the given name it is returned. 439 // Otherwise a new logger instance is created and registered 440 // in the LogManager global namespace. 441 // This method will always return a non-null Logger object. 442 // Synchronization is not required here. All synchronization for 443 // adding a new Logger object is handled by addLogger(). 444 // 445 // This method must delegate to the LogManager implementation to 446 // add a new Logger or return the one that has been added previously 447 // as a LogManager subclass may override the addLogger, getLogger, 448 // readConfiguration, and other methods. 449 Logger demandLogger(String name, String resourceBundleName, Class<?> caller) { 450 Logger result = getLogger(name); 451 if (result == null) { 452 // only allocate the new logger once 453 Logger newLogger = new Logger(name, resourceBundleName, caller); 454 do { 455 if (addLogger(newLogger)) { 456 // We successfully added the new Logger that we 457 // created above so return it without refetching. 458 return newLogger; 459 } 460 461 // We didn't add the new Logger that we created above 462 // because another thread added a Logger with the same 463 // name after our null check above and before our call 464 // to addLogger(). We have to refetch the Logger because 465 // addLogger() returns a boolean instead of the Logger 466 // reference itself. However, if the thread that created 467 // the other Logger is not holding a strong reference to 468 // the other Logger, then it is possible for the other 469 // Logger to be GC'ed after we saw it in addLogger() and 470 // before we can refetch it. If it has been GC'ed then 471 // we'll just loop around and try again. 472 result = getLogger(name); 473 } while (result == null); 474 } 475 return result; 476 } 477 478 Logger demandSystemLogger(String name, String resourceBundleName) { 479 // Add a system logger in the system context's namespace 480 final Logger sysLogger = systemContext.demandLogger(name, resourceBundleName); 481 482 // Add the system logger to the LogManager's namespace if not exist 483 // so that there is only one single logger of the given name. 484 // System loggers are visible to applications unless a logger of 485 // the same name has been added. 486 Logger logger; 487 do { 488 // First attempt to call addLogger instead of getLogger 489 // This would avoid potential bug in custom LogManager.getLogger 490 // implementation that adds a logger if does not exist 491 if (addLogger(sysLogger)) { 492 // successfully added the new system logger 493 logger = sysLogger; 494 } else { 495 logger = getLogger(name); 496 } 497 } while (logger == null); 498 499 // LogManager will set the sysLogger's handlers via LogManager.addLogger method. 500 if (logger != sysLogger && sysLogger.getHandlers().length == 0) { 501 // if logger already exists but handlers not set 502 final Logger l = logger; 503 AccessController.doPrivileged(new PrivilegedAction<Void>() { 504 public Void run() { 505 for (Handler hdl : l.getHandlers()) { 506 sysLogger.addHandler(hdl); 507 } 508 return null; 509 } 510 }); 511 } 512 return sysLogger; 513 } 514 515 // LoggerContext maintains the logger namespace per context. 516 // The default LogManager implementation has one system context and user 517 // context. The system context is used to maintain the namespace for 518 // all system loggers and is queried by the system code. If a system logger 519 // doesn't exist in the user context, it'll also be added to the user context. 520 // The user context is queried by the user code and all other loggers are 521 // added in the user context. 522 static class LoggerContext { 523 // Table of named Loggers that maps names to Loggers. 524 private final Hashtable<String,LoggerWeakRef> namedLoggers = new Hashtable<>(); 525 // Tree of named Loggers 526 private final LogNode root; 527 private final boolean requiresDefaultLoggers; 528 private LoggerContext() { 529 this(false); 530 } 531 private LoggerContext(boolean requiresDefaultLoggers) { 532 this.root = new LogNode(null, this); 533 this.requiresDefaultLoggers = requiresDefaultLoggers; 534 } 535 536 Logger demandLogger(String name, String resourceBundleName) { 537 // a LogManager subclass may have its own implementation to add and 538 // get a Logger. So delegate to the LogManager to do the work. 539 return manager.demandLogger(name, resourceBundleName, null); 540 } 541 542 543 // Due to subtle deadlock issues getUserContext() no longer 544 // calls addLocalLogger(rootLogger); 545 // Therefore - we need to add the default loggers later on. 546 // Checks that the context is properly initialized 547 // This is necessary before calling e.g. find(name) 548 // or getLoggerNames() 549 // 550 private void ensureInitialized() { 551 if (requiresDefaultLoggers) { 552 // Ensure that the root and global loggers are set. 553 ensureDefaultLogger(manager.rootLogger); 554 ensureDefaultLogger(Logger.global); 555 } 556 } 557 558 559 synchronized Logger findLogger(String name) { 560 // ensure that this context is properly initialized before 561 // looking for loggers. 562 ensureInitialized(); 563 LoggerWeakRef ref = namedLoggers.get(name); 564 if (ref == null) { 565 return null; 566 } 567 Logger logger = ref.get(); 568 if (logger == null) { 569 // Hashtable holds stale weak reference 570 // to a logger which has been GC-ed. 571 removeLogger(name); 572 } 573 return logger; 574 } 575 576 // This method is called before adding a logger to the 577 // context. 578 // 'logger' is the context that will be added. 579 // This method will ensure that the defaults loggers are added 580 // before adding 'logger'. 581 // 582 private void ensureAllDefaultLoggers(Logger logger) { 583 if (requiresDefaultLoggers) { 584 final String name = logger.getName(); 585 if (!name.isEmpty()) { 586 ensureDefaultLogger(manager.rootLogger); 587 } 588 if (!Logger.GLOBAL_LOGGER_NAME.equals(name)) { 589 ensureDefaultLogger(Logger.global); 590 } 591 } 592 } 593 594 private void ensureDefaultLogger(Logger logger) { 595 // Used for lazy addition of root logger and global logger 596 // to a LoggerContext. 597 598 // This check is simple sanity: we do not want that this 599 // method be called for anything else than Logger.global 600 // or owner.rootLogger. 601 if (!requiresDefaultLoggers || logger == null 602 || logger != Logger.global && logger != manager.rootLogger) { 603 604 // the case where we have a non null logger which is neither 605 // Logger.global nor manager.rootLogger indicates a serious 606 // issue - as ensureDefaultLogger should never be called 607 // with any other loggers than one of these two (or null - if 608 // e.g manager.rootLogger is not yet initialized)... 609 assert logger == null; 610 611 return; 612 } 613 614 // Adds the logger if it's not already there. 615 if (!namedLoggers.containsKey(logger.getName())) { 616 // It is important to prevent addLocalLogger to 617 // call ensureAllDefaultLoggers when we're in the process 618 // off adding one of those default loggers - as this would 619 // immediately cause a stack overflow. 620 // Therefore we must pass addDefaultLoggersIfNeeded=false, 621 // even if requiresDefaultLoggers is true. 622 addLocalLogger(logger, false); 623 } 624 } 625 626 boolean addLocalLogger(Logger logger) { 627 // no need to add default loggers if it's not required 628 return addLocalLogger(logger, requiresDefaultLoggers); 629 } 630 631 // Add a logger to this context. This method will only set its level 632 // and process parent loggers. It doesn't set its handlers. 633 synchronized boolean addLocalLogger(Logger logger, boolean addDefaultLoggersIfNeeded) { 634 // addDefaultLoggersIfNeeded serves to break recursion when adding 635 // default loggers. If we're adding one of the default loggers 636 // (we're being called from ensureDefaultLogger()) then 637 // addDefaultLoggersIfNeeded will be false: we don't want to 638 // call ensureAllDefaultLoggers again. 639 // 640 // Note: addDefaultLoggersIfNeeded can also be false when 641 // requiresDefaultLoggers is false - since calling 642 // ensureAllDefaultLoggers would have no effect in this case. 643 if (addDefaultLoggersIfNeeded) { 644 ensureAllDefaultLoggers(logger); 645 } 646 647 final String name = logger.getName(); 648 if (name == null) { 649 throw new NullPointerException(); 650 } 651 LoggerWeakRef ref = namedLoggers.get(name); 652 if (ref != null) { 653 if (ref.get() == null) { 654 // It's possible that the Logger was GC'ed after a 655 // drainLoggerRefQueueBounded() call above so allow 656 // a new one to be registered. 657 removeLogger(name); 658 } else { 659 // We already have a registered logger with the given name. 660 return false; 661 } 662 } 663 664 // We're adding a new logger. 665 // Note that we are creating a weak reference here. 666 ref = manager.new LoggerWeakRef(logger); 667 namedLoggers.put(name, ref); 668 669 // Apply any initial level defined for the new logger. 670 Level level = manager.getLevelProperty(name + ".level", null); 671 if (level != null) { 672 doSetLevel(logger, level); 673 } 674 675 // instantiation of the handler is done in the LogManager.addLogger 676 // implementation as a handler class may be only visible to LogManager 677 // subclass for the custom log manager case 678 processParentHandlers(logger, name); 679 680 // Find the new node and its parent. 681 LogNode node = getNode(name); 682 node.loggerRef = ref; 683 Logger parent = null; 684 LogNode nodep = node.parent; 685 while (nodep != null) { 686 LoggerWeakRef nodeRef = nodep.loggerRef; 687 if (nodeRef != null) { 688 parent = nodeRef.get(); 689 if (parent != null) { 690 break; 691 } 692 } 693 nodep = nodep.parent; 694 } 695 696 if (parent != null) { 697 doSetParent(logger, parent); 698 } 699 // Walk over the children and tell them we are their new parent. 700 node.walkAndSetParent(logger); 701 // new LogNode is ready so tell the LoggerWeakRef about it 702 ref.setNode(node); 703 return true; 704 } 705 706 // note: all calls to removeLogger are synchronized on LogManager's 707 // intrinsic lock 708 void removeLogger(String name) { 709 namedLoggers.remove(name); 710 } 711 712 synchronized Enumeration<String> getLoggerNames() { 713 // ensure that this context is properly initialized before 714 // returning logger names. 715 ensureInitialized(); 716 return namedLoggers.keys(); 717 } 718 719 // If logger.getUseParentHandlers() returns 'true' and any of the logger's 720 // parents have levels or handlers defined, make sure they are instantiated. 721 private void processParentHandlers(final Logger logger, final String name) { 722 AccessController.doPrivileged(new PrivilegedAction<Void>() { 723 public Void run() { 724 if (logger != manager.rootLogger) { 725 boolean useParent = manager.getBooleanProperty(name + ".useParentHandlers", true); 726 if (!useParent) { 727 logger.setUseParentHandlers(false); 728 } 729 } 730 return null; 731 } 732 }); 733 734 int ix = 1; 735 for (;;) { 736 int ix2 = name.indexOf(".", ix); 737 if (ix2 < 0) { 738 break; 739 } 740 String pname = name.substring(0, ix2); 741 if (manager.getProperty(pname + ".level") != null || 742 manager.getProperty(pname + ".handlers") != null) { 743 // This pname has a level/handlers definition. 744 // Make sure it exists. 745 demandLogger(pname, null); 746 } 747 ix = ix2+1; 748 } 749 } 750 751 // Gets a node in our tree of logger nodes. 752 // If necessary, create it. 753 LogNode getNode(String name) { 754 if (name == null || name.equals("")) { 755 return root; 756 } 757 LogNode node = root; 758 while (name.length() > 0) { 759 int ix = name.indexOf("."); 760 String head; 761 if (ix > 0) { 762 head = name.substring(0, ix); 763 name = name.substring(ix + 1); 764 } else { 765 head = name; 766 name = ""; 767 } 768 if (node.children == null) { 769 node.children = new HashMap<>(); 770 } 771 LogNode child = node.children.get(head); 772 if (child == null) { 773 child = new LogNode(node, this); 774 node.children.put(head, child); 775 } 776 node = child; 777 } 778 return node; 779 } 780 } 781 782 static class SystemLoggerContext extends LoggerContext { 783 // Add a system logger in the system context's namespace as well as 784 // in the LogManager's namespace if not exist so that there is only 785 // one single logger of the given name. System loggers are visible 786 // to applications unless a logger of the same name has been added. 787 Logger demandLogger(String name, String resourceBundleName) { 788 Logger result = findLogger(name); 789 if (result == null) { 790 // only allocate the new system logger once 791 Logger newLogger = new Logger(name, resourceBundleName); 792 do { 793 if (addLocalLogger(newLogger)) { 794 // We successfully added the new Logger that we 795 // created above so return it without refetching. 796 result = newLogger; 797 } else { 798 // We didn't add the new Logger that we created above 799 // because another thread added a Logger with the same 800 // name after our null check above and before our call 801 // to addLogger(). We have to refetch the Logger because 802 // addLogger() returns a boolean instead of the Logger 803 // reference itself. However, if the thread that created 804 // the other Logger is not holding a strong reference to 805 // the other Logger, then it is possible for the other 806 // Logger to be GC'ed after we saw it in addLogger() and 807 // before we can refetch it. If it has been GC'ed then 808 // we'll just loop around and try again. 809 result = findLogger(name); 810 } 811 } while (result == null); 812 } 813 return result; 814 } 815 } 816 817 // Add new per logger handlers. 818 // We need to raise privilege here. All our decisions will 819 // be made based on the logging configuration, which can 820 // only be modified by trusted code. 821 private void loadLoggerHandlers(final Logger logger, final String name, 822 final String handlersPropertyName) 823 { 824 AccessController.doPrivileged(new PrivilegedAction<Object>() { 825 public Object run() { 826 String names[] = parseClassNames(handlersPropertyName); 827 for (int i = 0; i < names.length; i++) { 828 String word = names[i]; 829 try { 830 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word); 831 Handler hdl = (Handler) clz.newInstance(); 832 // Check if there is a property defining the 833 // this handler's level. 834 String levs = getProperty(word + ".level"); 835 if (levs != null) { 836 Level l = Level.findLevel(levs); 837 if (l != null) { 838 hdl.setLevel(l); 839 } else { 840 // Probably a bad level. Drop through. 841 System.err.println("Can't set level for " + word); 842 } 843 } 844 // Add this Handler to the logger 845 logger.addHandler(hdl); 846 } catch (Exception ex) { 847 System.err.println("Can't load log handler \"" + word + "\""); 848 System.err.println("" + ex); 849 ex.printStackTrace(); 850 } 851 } 852 return null; 853 } 854 }); 855 } 856 857 858 // loggerRefQueue holds LoggerWeakRef objects for Logger objects 859 // that have been GC'ed. 860 private final ReferenceQueue<Logger> loggerRefQueue 861 = new ReferenceQueue<>(); 862 863 // Package-level inner class. 864 // Helper class for managing WeakReferences to Logger objects. 865 // 866 // LogManager.namedLoggers 867 // - has weak references to all named Loggers 868 // - namedLoggers keeps the LoggerWeakRef objects for the named 869 // Loggers around until we can deal with the book keeping for 870 // the named Logger that is being GC'ed. 871 // LogManager.LogNode.loggerRef 872 // - has a weak reference to a named Logger 873 // - the LogNode will also keep the LoggerWeakRef objects for 874 // the named Loggers around; currently LogNodes never go away. 875 // Logger.kids 876 // - has a weak reference to each direct child Logger; this 877 // includes anonymous and named Loggers 878 // - anonymous Loggers are always children of the rootLogger 879 // which is a strong reference; rootLogger.kids keeps the 880 // LoggerWeakRef objects for the anonymous Loggers around 881 // until we can deal with the book keeping. 882 // 883 final class LoggerWeakRef extends WeakReference<Logger> { 884 private String name; // for namedLoggers cleanup 885 private LogNode node; // for loggerRef cleanup 886 private WeakReference<Logger> parentRef; // for kids cleanup 887 888 LoggerWeakRef(Logger logger) { 889 super(logger, loggerRefQueue); 890 891 name = logger.getName(); // save for namedLoggers cleanup 892 } 893 894 // dispose of this LoggerWeakRef object 895 void dispose() { 896 if (node != null) { 897 // if we have a LogNode, then we were a named Logger 898 // so clear namedLoggers weak ref to us 899 node.context.removeLogger(name); 900 name = null; // clear our ref to the Logger's name 901 902 node.loggerRef = null; // clear LogNode's weak ref to us 903 node = null; // clear our ref to LogNode 904 } 905 906 if (parentRef != null) { 907 // this LoggerWeakRef has or had a parent Logger 908 Logger parent = parentRef.get(); 909 if (parent != null) { 910 // the parent Logger is still there so clear the 911 // parent Logger's weak ref to us 912 parent.removeChildLogger(this); 913 } 914 parentRef = null; // clear our weak ref to the parent Logger 915 } 916 } 917 918 // set the node field to the specified value 919 void setNode(LogNode node) { 920 this.node = node; 921 } 922 923 // set the parentRef field to the specified value 924 void setParentRef(WeakReference<Logger> parentRef) { 925 this.parentRef = parentRef; 926 } 927 } 928 929 // Package-level method. 930 // Drain some Logger objects that have been GC'ed. 931 // 932 // drainLoggerRefQueueBounded() is called by addLogger() below 933 // and by Logger.getAnonymousLogger(String) so we'll drain up to 934 // MAX_ITERATIONS GC'ed Loggers for every Logger we add. 935 // 936 // On a WinXP VMware client, a MAX_ITERATIONS value of 400 gives 937 // us about a 50/50 mix in increased weak ref counts versus 938 // decreased weak ref counts in the AnonLoggerWeakRefLeak test. 939 // Here are stats for cleaning up sets of 400 anonymous Loggers: 940 // - test duration 1 minute 941 // - sample size of 125 sets of 400 942 // - average: 1.99 ms 943 // - minimum: 0.57 ms 944 // - maximum: 25.3 ms 945 // 946 // The same config gives us a better decreased weak ref count 947 // than increased weak ref count in the LoggerWeakRefLeak test. 948 // Here are stats for cleaning up sets of 400 named Loggers: 949 // - test duration 2 minutes 950 // - sample size of 506 sets of 400 951 // - average: 0.57 ms 952 // - minimum: 0.02 ms 953 // - maximum: 10.9 ms 954 // 955 private final static int MAX_ITERATIONS = 400; 956 final synchronized void drainLoggerRefQueueBounded() { 957 for (int i = 0; i < MAX_ITERATIONS; i++) { 958 if (loggerRefQueue == null) { 959 // haven't finished loading LogManager yet 960 break; 961 } 962 963 LoggerWeakRef ref = (LoggerWeakRef) loggerRefQueue.poll(); 964 if (ref == null) { 965 break; 966 } 967 // a Logger object has been GC'ed so clean it up 968 ref.dispose(); 969 } 970 } 971 972 /** 973 * Add a named logger. This does nothing and returns false if a logger 974 * with the same name is already registered. 975 * <p> 976 * The Logger factory methods call this method to register each 977 * newly created Logger. 978 * <p> 979 * The application should retain its own reference to the Logger 980 * object to avoid it being garbage collected. The LogManager 981 * may only retain a weak reference. 982 * 983 * @param logger the new logger. 984 * @return true if the argument logger was registered successfully, 985 * false if a logger of that name already exists. 986 * @exception NullPointerException if the logger name is null. 987 */ 988 public boolean addLogger(Logger logger) { 989 final String name = logger.getName(); 990 if (name == null) { 991 throw new NullPointerException(); 992 } 993 drainLoggerRefQueueBounded(); 994 LoggerContext cx = getUserContext(); 995 if (cx.addLocalLogger(logger)) { 996 // Do we have a per logger handler too? 997 // Note: this will add a 200ms penalty 998 loadLoggerHandlers(logger, name, name + ".handlers"); 999 return true; 1000 } else { 1001 return false; 1002 } 1003 } 1004 1005 // Private method to set a level on a logger. 1006 // If necessary, we raise privilege before doing the call. 1007 private static void doSetLevel(final Logger logger, final Level level) { 1008 SecurityManager sm = System.getSecurityManager(); 1009 if (sm == null) { 1010 // There is no security manager, so things are easy. 1011 logger.setLevel(level); 1012 return; 1013 } 1014 // There is a security manager. Raise privilege before 1015 // calling setLevel. 1016 AccessController.doPrivileged(new PrivilegedAction<Object>() { 1017 public Object run() { 1018 logger.setLevel(level); 1019 return null; 1020 }}); 1021 } 1022 1023 // Private method to set a parent on a logger. 1024 // If necessary, we raise privilege before doing the setParent call. 1025 private static void doSetParent(final Logger logger, final Logger parent) { 1026 SecurityManager sm = System.getSecurityManager(); 1027 if (sm == null) { 1028 // There is no security manager, so things are easy. 1029 logger.setParent(parent); 1030 return; 1031 } 1032 // There is a security manager. Raise privilege before 1033 // calling setParent. 1034 AccessController.doPrivileged(new PrivilegedAction<Object>() { 1035 public Object run() { 1036 logger.setParent(parent); 1037 return null; 1038 }}); 1039 } 1040 1041 /** 1042 * Method to find a named logger. 1043 * <p> 1044 * Note that since untrusted code may create loggers with 1045 * arbitrary names this method should not be relied on to 1046 * find Loggers for security sensitive logging. 1047 * It is also important to note that the Logger associated with the 1048 * String {@code name} may be garbage collected at any time if there 1049 * is no strong reference to the Logger. The caller of this method 1050 * must check the return value for null in order to properly handle 1051 * the case where the Logger has been garbage collected. 1052 * <p> 1053 * @param name name of the logger 1054 * @return matching logger or null if none is found 1055 */ 1056 public Logger getLogger(String name) { 1057 return getUserContext().findLogger(name); 1058 } 1059 1060 /** 1061 * Get an enumeration of known logger names. 1062 * <p> 1063 * Note: Loggers may be added dynamically as new classes are loaded. 1064 * This method only reports on the loggers that are currently registered. 1065 * It is also important to note that this method only returns the name 1066 * of a Logger, not a strong reference to the Logger itself. 1067 * The returned String does nothing to prevent the Logger from being 1068 * garbage collected. In particular, if the returned name is passed 1069 * to {@code LogManager.getLogger()}, then the caller must check the 1070 * return value from {@code LogManager.getLogger()} for null to properly 1071 * handle the case where the Logger has been garbage collected in the 1072 * time since its name was returned by this method. 1073 * <p> 1074 * @return enumeration of logger name strings 1075 */ 1076 public Enumeration<String> getLoggerNames() { 1077 return getUserContext().getLoggerNames(); 1078 } 1079 1080 /** 1081 * Reinitialize the logging properties and reread the logging configuration. 1082 * <p> 1083 * The same rules are used for locating the configuration properties 1084 * as are used at startup. So normally the logging properties will 1085 * be re-read from the same file that was used at startup. 1086 * <P> 1087 * Any log level definitions in the new configuration file will be 1088 * applied using Logger.setLevel(), if the target Logger exists. 1089 * <p> 1090 * A PropertyChangeEvent will be fired after the properties are read. 1091 * 1092 * @exception SecurityException if a security manager exists and if 1093 * the caller does not have LoggingPermission("control"). 1094 * @exception IOException if there are IO problems reading the configuration. 1095 */ 1096 public void readConfiguration() throws IOException, SecurityException { 1097 checkPermission(); 1098 1099 // if a configuration class is specified, load it and use it. 1100 String cname = System.getProperty("java.util.logging.config.class"); 1101 if (cname != null) { 1102 try { 1103 // Instantiate the named class. It is its constructor's 1104 // responsibility to initialize the logging configuration, by 1105 // calling readConfiguration(InputStream) with a suitable stream. 1106 try { 1107 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(cname); 1108 clz.newInstance(); 1109 return; 1110 } catch (ClassNotFoundException ex) { 1111 Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(cname); 1112 clz.newInstance(); 1113 return; 1114 } 1115 } catch (Exception ex) { 1116 System.err.println("Logging configuration class \"" + cname + "\" failed"); 1117 System.err.println("" + ex); 1118 // keep going and useful config file. 1119 } 1120 } 1121 1122 String fname = System.getProperty("java.util.logging.config.file"); 1123 if (fname == null) { 1124 fname = System.getProperty("java.home"); 1125 if (fname == null) { 1126 throw new Error("Can't find java.home ??"); 1127 } 1128 File f = new File(fname, "lib"); 1129 f = new File(f, "logging.properties"); 1130 fname = f.getCanonicalPath(); 1131 } 1132 InputStream in = new FileInputStream(fname); 1133 BufferedInputStream bin = new BufferedInputStream(in); 1134 try { 1135 readConfiguration(bin); 1136 } finally { 1137 if (in != null) { 1138 in.close(); 1139 } 1140 } 1141 } 1142 1143 /** 1144 * Reset the logging configuration. 1145 * <p> 1146 * For all named loggers, the reset operation removes and closes 1147 * all Handlers and (except for the root logger) sets the level 1148 * to null. The root logger's level is set to Level.INFO. 1149 * 1150 * @exception SecurityException if a security manager exists and if 1151 * the caller does not have LoggingPermission("control"). 1152 */ 1153 1154 public void reset() throws SecurityException { 1155 checkPermission(); 1156 synchronized (this) { 1157 props = new Properties(); 1158 // Since we are doing a reset we no longer want to initialize 1159 // the global handlers, if they haven't been initialized yet. 1160 initializedGlobalHandlers = true; 1161 } 1162 for (LoggerContext cx : contexts()) { 1163 Enumeration<String> enum_ = cx.getLoggerNames(); 1164 while (enum_.hasMoreElements()) { 1165 String name = enum_.nextElement(); 1166 Logger logger = cx.findLogger(name); 1167 if (logger != null) { 1168 resetLogger(logger); 1169 } 1170 } 1171 } 1172 } 1173 1174 // Private method to reset an individual target logger. 1175 private void resetLogger(Logger logger) { 1176 // Close all the Logger's handlers. 1177 Handler[] targets = logger.getHandlers(); 1178 for (int i = 0; i < targets.length; i++) { 1179 Handler h = targets[i]; 1180 logger.removeHandler(h); 1181 try { 1182 h.close(); 1183 } catch (Exception ex) { 1184 // Problems closing a handler? Keep going... 1185 } 1186 } 1187 String name = logger.getName(); 1188 if (name != null && name.equals("")) { 1189 // This is the root logger. 1190 logger.setLevel(defaultLevel); 1191 } else { 1192 logger.setLevel(null); 1193 } 1194 } 1195 1196 // get a list of whitespace separated classnames from a property. 1197 private String[] parseClassNames(String propertyName) { 1198 String hands = getProperty(propertyName); 1199 if (hands == null) { 1200 return new String[0]; 1201 } 1202 hands = hands.trim(); 1203 int ix = 0; 1204 Vector<String> result = new Vector<>(); 1205 while (ix < hands.length()) { 1206 int end = ix; 1207 while (end < hands.length()) { 1208 if (Character.isWhitespace(hands.charAt(end))) { 1209 break; 1210 } 1211 if (hands.charAt(end) == ',') { 1212 break; 1213 } 1214 end++; 1215 } 1216 String word = hands.substring(ix, end); 1217 ix = end+1; 1218 word = word.trim(); 1219 if (word.length() == 0) { 1220 continue; 1221 } 1222 result.add(word); 1223 } 1224 return result.toArray(new String[result.size()]); 1225 } 1226 1227 /** 1228 * Reinitialize the logging properties and reread the logging configuration 1229 * from the given stream, which should be in java.util.Properties format. 1230 * A PropertyChangeEvent will be fired after the properties are read. 1231 * <p> 1232 * Any log level definitions in the new configuration file will be 1233 * applied using Logger.setLevel(), if the target Logger exists. 1234 * 1235 * @param ins stream to read properties from 1236 * @exception SecurityException if a security manager exists and if 1237 * the caller does not have LoggingPermission("control"). 1238 * @exception IOException if there are problems reading from the stream. 1239 */ 1240 public void readConfiguration(InputStream ins) throws IOException, SecurityException { 1241 checkPermission(); 1242 reset(); 1243 1244 // Load the properties 1245 props.load(ins); 1246 // Instantiate new configuration objects. 1247 String names[] = parseClassNames("config"); 1248 1249 for (int i = 0; i < names.length; i++) { 1250 String word = names[i]; 1251 try { 1252 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word); 1253 clz.newInstance(); 1254 } catch (Exception ex) { 1255 System.err.println("Can't load config class \"" + word + "\""); 1256 System.err.println("" + ex); 1257 // ex.printStackTrace(); 1258 } 1259 } 1260 1261 // Set levels on any pre-existing loggers, based on the new properties. 1262 setLevelsOnExistingLoggers(); 1263 1264 // Notify any interested parties that our properties have changed. 1265 // We first take a copy of the listener map so that we aren't holding any 1266 // locks when calling the listeners. 1267 Map<Object,Integer> listeners = null; 1268 synchronized (listenerMap) { 1269 if (!listenerMap.isEmpty()) 1270 listeners = new HashMap<>(listenerMap); 1271 } 1272 if (listeners != null) { 1273 assert Beans.isBeansPresent(); 1274 Object ev = Beans.newPropertyChangeEvent(LogManager.class, null, null, null); 1275 for (Map.Entry<Object,Integer> entry : listeners.entrySet()) { 1276 Object listener = entry.getKey(); 1277 int count = entry.getValue().intValue(); 1278 for (int i = 0; i < count; i++) { 1279 Beans.invokePropertyChange(listener, ev); 1280 } 1281 } 1282 } 1283 1284 1285 // Note that we need to reinitialize global handles when 1286 // they are first referenced. 1287 synchronized (this) { 1288 initializedGlobalHandlers = false; 1289 } 1290 } 1291 1292 /** 1293 * Get the value of a logging property. 1294 * The method returns null if the property is not found. 1295 * @param name property name 1296 * @return property value 1297 */ 1298 public String getProperty(String name) { 1299 return props.getProperty(name); 1300 } 1301 1302 // Package private method to get a String property. 1303 // If the property is not defined we return the given 1304 // default value. 1305 String getStringProperty(String name, String defaultValue) { 1306 String val = getProperty(name); 1307 if (val == null) { 1308 return defaultValue; 1309 } 1310 return val.trim(); 1311 } 1312 1313 // Package private method to get an integer property. 1314 // If the property is not defined or cannot be parsed 1315 // we return the given default value. 1316 int getIntProperty(String name, int defaultValue) { 1317 String val = getProperty(name); 1318 if (val == null) { 1319 return defaultValue; 1320 } 1321 try { 1322 return Integer.parseInt(val.trim()); 1323 } catch (Exception ex) { 1324 return defaultValue; 1325 } 1326 } 1327 1328 // Package private method to get a boolean property. 1329 // If the property is not defined or cannot be parsed 1330 // we return the given default value. 1331 boolean getBooleanProperty(String name, boolean defaultValue) { 1332 String val = getProperty(name); 1333 if (val == null) { 1334 return defaultValue; 1335 } 1336 val = val.toLowerCase(); 1337 if (val.equals("true") || val.equals("1")) { 1338 return true; 1339 } else if (val.equals("false") || val.equals("0")) { 1340 return false; 1341 } 1342 return defaultValue; 1343 } 1344 1345 // Package private method to get a Level property. 1346 // If the property is not defined or cannot be parsed 1347 // we return the given default value. 1348 Level getLevelProperty(String name, Level defaultValue) { 1349 String val = getProperty(name); 1350 if (val == null) { 1351 return defaultValue; 1352 } 1353 Level l = Level.findLevel(val.trim()); 1354 return l != null ? l : defaultValue; 1355 } 1356 1357 // Package private method to get a filter property. 1358 // We return an instance of the class named by the "name" 1359 // property. If the property is not defined or has problems 1360 // we return the defaultValue. 1361 Filter getFilterProperty(String name, Filter defaultValue) { 1362 String val = getProperty(name); 1363 try { 1364 if (val != null) { 1365 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(val); 1366 return (Filter) clz.newInstance(); 1367 } 1368 } catch (Exception ex) { 1369 // We got one of a variety of exceptions in creating the 1370 // class or creating an instance. 1371 // Drop through. 1372 } 1373 // We got an exception. Return the defaultValue. 1374 return defaultValue; 1375 } 1376 1377 1378 // Package private method to get a formatter property. 1379 // We return an instance of the class named by the "name" 1380 // property. If the property is not defined or has problems 1381 // we return the defaultValue. 1382 Formatter getFormatterProperty(String name, Formatter defaultValue) { 1383 String val = getProperty(name); 1384 try { 1385 if (val != null) { 1386 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(val); 1387 return (Formatter) clz.newInstance(); 1388 } 1389 } catch (Exception ex) { 1390 // We got one of a variety of exceptions in creating the 1391 // class or creating an instance. 1392 // Drop through. 1393 } 1394 // We got an exception. Return the defaultValue. 1395 return defaultValue; 1396 } 1397 1398 // Private method to load the global handlers. 1399 // We do the real work lazily, when the global handlers 1400 // are first used. 1401 private synchronized void initializeGlobalHandlers() { 1402 if (initializedGlobalHandlers) { 1403 return; 1404 } 1405 1406 initializedGlobalHandlers = true; 1407 1408 if (deathImminent) { 1409 // Aaargh... 1410 // The VM is shutting down and our exit hook has been called. 1411 // Avoid allocating global handlers. 1412 return; 1413 } 1414 loadLoggerHandlers(rootLogger, null, "handlers"); 1415 } 1416 1417 private final Permission controlPermission = new LoggingPermission("control", null); 1418 1419 void checkPermission() { 1420 SecurityManager sm = System.getSecurityManager(); 1421 if (sm != null) 1422 sm.checkPermission(controlPermission); 1423 } 1424 1425 /** 1426 * Check that the current context is trusted to modify the logging 1427 * configuration. This requires LoggingPermission("control"). 1428 * <p> 1429 * If the check fails we throw a SecurityException, otherwise 1430 * we return normally. 1431 * 1432 * @exception SecurityException if a security manager exists and if 1433 * the caller does not have LoggingPermission("control"). 1434 */ 1435 public void checkAccess() throws SecurityException { 1436 checkPermission(); 1437 } 1438 1439 // Nested class to represent a node in our tree of named loggers. 1440 private static class LogNode { 1441 HashMap<String,LogNode> children; 1442 LoggerWeakRef loggerRef; 1443 LogNode parent; 1444 final LoggerContext context; 1445 1446 LogNode(LogNode parent, LoggerContext context) { 1447 this.parent = parent; 1448 this.context = context; 1449 } 1450 1451 // Recursive method to walk the tree below a node and set 1452 // a new parent logger. 1453 void walkAndSetParent(Logger parent) { 1454 if (children == null) { 1455 return; 1456 } 1457 Iterator<LogNode> values = children.values().iterator(); 1458 while (values.hasNext()) { 1459 LogNode node = values.next(); 1460 LoggerWeakRef ref = node.loggerRef; 1461 Logger logger = (ref == null) ? null : ref.get(); 1462 if (logger == null) { 1463 node.walkAndSetParent(parent); 1464 } else { 1465 doSetParent(logger, parent); 1466 } 1467 } 1468 } 1469 } 1470 1471 // We use a subclass of Logger for the root logger, so 1472 // that we only instantiate the global handlers when they 1473 // are first needed. 1474 private class RootLogger extends Logger { 1475 private RootLogger() { 1476 super("", null); 1477 setLevel(defaultLevel); 1478 } 1479 1480 public void log(LogRecord record) { 1481 // Make sure that the global handlers have been instantiated. 1482 initializeGlobalHandlers(); 1483 super.log(record); 1484 } 1485 1486 public void addHandler(Handler h) { 1487 initializeGlobalHandlers(); 1488 super.addHandler(h); 1489 } 1490 1491 public void removeHandler(Handler h) { 1492 initializeGlobalHandlers(); 1493 super.removeHandler(h); 1494 } 1495 1496 public Handler[] getHandlers() { 1497 initializeGlobalHandlers(); 1498 return super.getHandlers(); 1499 } 1500 } 1501 1502 1503 // Private method to be called when the configuration has 1504 // changed to apply any level settings to any pre-existing loggers. 1505 synchronized private void setLevelsOnExistingLoggers() { 1506 Enumeration<?> enum_ = props.propertyNames(); 1507 while (enum_.hasMoreElements()) { 1508 String key = (String)enum_.nextElement(); 1509 if (!key.endsWith(".level")) { 1510 // Not a level definition. 1511 continue; 1512 } 1513 int ix = key.length() - 6; 1514 String name = key.substring(0, ix); 1515 Level level = getLevelProperty(key, null); 1516 if (level == null) { 1517 System.err.println("Bad level value for property: " + key); 1518 continue; 1519 } 1520 for (LoggerContext cx : contexts()) { 1521 Logger l = cx.findLogger(name); 1522 if (l == null) { 1523 continue; 1524 } 1525 l.setLevel(level); 1526 } 1527 } 1528 } 1529 1530 // Management Support 1531 private static LoggingMXBean loggingMXBean = null; 1532 /** 1533 * String representation of the 1534 * {@link javax.management.ObjectName} for the management interface 1535 * for the logging facility. 1536 * 1537 * @see java.lang.management.PlatformLoggingMXBean 1538 * @see java.util.logging.LoggingMXBean 1539 * 1540 * @since 1.5 1541 */ 1542 public final static String LOGGING_MXBEAN_NAME 1543 = "java.util.logging:type=Logging"; 1544 1545 /** 1546 * Returns <tt>LoggingMXBean</tt> for managing loggers. 1547 * An alternative way to manage loggers is through the 1548 * {@link java.lang.management.PlatformLoggingMXBean} interface 1549 * that can be obtained by calling: 1550 * <pre> 1551 * PlatformLoggingMXBean logging = {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class) 1552 * ManagementFactory.getPlatformMXBean}(PlatformLoggingMXBean.class); 1553 * </pre> 1554 * 1555 * @return a {@link LoggingMXBean} object. 1556 * 1557 * @see java.lang.management.PlatformLoggingMXBean 1558 * @since 1.5 1559 */ 1560 public static synchronized LoggingMXBean getLoggingMXBean() { 1561 if (loggingMXBean == null) { 1562 loggingMXBean = new Logging(); 1563 } 1564 return loggingMXBean; 1565 } 1566 1567 /** 1568 * A class that provides access to the java.beans.PropertyChangeListener 1569 * and java.beans.PropertyChangeEvent without creating a static dependency 1570 * on java.beans. This class can be removed once the addPropertyChangeListener 1571 * and removePropertyChangeListener methods are removed. 1572 */ 1573 private static class Beans { 1574 private static final Class<?> propertyChangeListenerClass = 1575 getClass("java.beans.PropertyChangeListener"); 1576 1577 private static final Class<?> propertyChangeEventClass = 1578 getClass("java.beans.PropertyChangeEvent"); 1579 1580 private static final Method propertyChangeMethod = 1581 getMethod(propertyChangeListenerClass, 1582 "propertyChange", 1583 propertyChangeEventClass); 1584 1585 private static final Constructor<?> propertyEventCtor = 1586 getConstructor(propertyChangeEventClass, 1587 Object.class, 1588 String.class, 1589 Object.class, 1590 Object.class); 1591 1592 private static Class<?> getClass(String name) { 1593 try { 1594 return Class.forName(name, true, Beans.class.getClassLoader()); 1595 } catch (ClassNotFoundException e) { 1596 return null; 1597 } 1598 } 1599 private static Constructor<?> getConstructor(Class<?> c, Class<?>... types) { 1600 try { 1601 return (c == null) ? null : c.getDeclaredConstructor(types); 1602 } catch (NoSuchMethodException x) { 1603 throw new AssertionError(x); 1604 } 1605 } 1606 1607 private static Method getMethod(Class<?> c, String name, Class<?>... types) { 1608 try { 1609 return (c == null) ? null : c.getMethod(name, types); 1610 } catch (NoSuchMethodException e) { 1611 throw new AssertionError(e); 1612 } 1613 } 1614 1615 /** 1616 * Returns {@code true} if java.beans is present. 1617 */ 1618 static boolean isBeansPresent() { 1619 return propertyChangeListenerClass != null && 1620 propertyChangeEventClass != null; 1621 } 1622 1623 /** 1624 * Returns a new PropertyChangeEvent with the given source, property 1625 * name, old and new values. 1626 */ 1627 static Object newPropertyChangeEvent(Object source, String prop, 1628 Object oldValue, Object newValue) 1629 { 1630 try { 1631 return propertyEventCtor.newInstance(source, prop, oldValue, newValue); 1632 } catch (InstantiationException | IllegalAccessException x) { 1633 throw new AssertionError(x); 1634 } catch (InvocationTargetException x) { 1635 Throwable cause = x.getCause(); 1636 if (cause instanceof Error) 1637 throw (Error)cause; 1638 if (cause instanceof RuntimeException) 1639 throw (RuntimeException)cause; 1640 throw new AssertionError(x); 1641 } 1642 } 1643 1644 /** 1645 * Invokes the given PropertyChangeListener's propertyChange method 1646 * with the given event. 1647 */ 1648 static void invokePropertyChange(Object listener, Object ev) { 1649 try { 1650 propertyChangeMethod.invoke(listener, ev); 1651 } catch (IllegalAccessException x) { 1652 throw new AssertionError(x); 1653 } catch (InvocationTargetException x) { 1654 Throwable cause = x.getCause(); 1655 if (cause instanceof Error) 1656 throw (Error)cause; 1657 if (cause instanceof RuntimeException) 1658 throw (RuntimeException)cause; 1659 throw new AssertionError(x); 1660 } 1661 } 1662 } 1663 }