LogManager.java 62.0 KB
Newer Older
D
duke 已提交
1
/*
J
jgish 已提交
2
 * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31
 */


package java.util.logging;

import java.io.*;
import java.util.*;
import java.security.*;
32
import java.lang.ref.ReferenceQueue;
D
duke 已提交
33
import java.lang.ref.WeakReference;
34 35 36
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
D
duke 已提交
37
import java.beans.PropertyChangeListener;
M
mchung 已提交
38 39
import sun.misc.JavaAWTAccess;
import sun.misc.SharedSecrets;
D
duke 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

/**
 * There is a single global LogManager object that is used to
 * maintain a set of shared state about Loggers and log services.
 * <p>
 * This LogManager object:
 * <ul>
 * <li> Manages a hierarchical namespace of Logger objects.  All
 *      named Loggers are stored in this namespace.
 * <li> Manages a set of logging control properties.  These are
 *      simple key-value pairs that can be used by Handlers and
 *      other logging objects to configure themselves.
 * </ul>
 * <p>
 * The global LogManager object can be retrieved using LogManager.getLogManager().
 * The LogManager object is created during class initialization and
 * cannot subsequently be changed.
 * <p>
 * At startup the LogManager class is located using the
 * java.util.logging.manager system property.
 * <p>
61 62
 * The LogManager defines two optional system properties that allow control over
 * the initial configuration:
D
duke 已提交
63 64 65 66
 * <ul>
 * <li>"java.util.logging.config.class"
 * <li>"java.util.logging.config.file"
 * </ul>
67 68
 * These two properties may be specified on the command line to the "java"
 * command, or as system property definitions passed to JNI_CreateJavaVM.
D
duke 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82
 * <p>
 * If the "java.util.logging.config.class" property is set, then the
 * property value is treated as a class name.  The given class will be
 * loaded, an object will be instantiated, and that object's constructor
 * is responsible for reading in the initial configuration.  (That object
 * may use other system properties to control its configuration.)  The
 * alternate configuration class can use <tt>readConfiguration(InputStream)</tt>
 * to define properties in the LogManager.
 * <p>
 * If "java.util.logging.config.class" property is <b>not</b> set,
 * then the "java.util.logging.config.file" system property can be used
 * to specify a properties file (in java.util.Properties format). The
 * initial logging configuration will be read from this file.
 * <p>
83 84 85 86
 * If neither of these properties is defined then the LogManager uses its
 * default configuration. The default configuration is typically loaded from the
 * properties file "{@code lib/logging.properties}" in the Java installation
 * directory.
D
duke 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
 * <p>
 * The properties for loggers and Handlers will have names starting
 * with the dot-separated name for the handler or logger.
 * <p>
 * The global logging properties may include:
 * <ul>
 * <li>A property "handlers".  This defines a whitespace or comma separated
 * list of class names for handler classes to load and register as
 * handlers on the root Logger (the Logger named "").  Each class
 * name must be for a Handler class which has a default constructor.
 * Note that these Handlers may be created lazily, when they are
 * first used.
 *
 * <li>A property "&lt;logger&gt;.handlers". This defines a whitespace or
 * comma separated list of class names for handlers classes to
 * load and register as handlers to the specified logger. Each class
 * name must be for a Handler class which has a default constructor.
 * Note that these Handlers may be created lazily, when they are
 * first used.
 *
 * <li>A property "&lt;logger&gt;.useParentHandlers". This defines a boolean
 * value. By default every logger calls its parent in addition to
 * handling the logging message itself, this often result in messages
 * being handled by the root logger as well. When setting this property
 * to false a Handler needs to be configured for this logger otherwise
 * no logging messages are delivered.
 *
 * <li>A property "config".  This property is intended to allow
 * arbitrary configuration code to be run.  The property defines a
 * whitespace or comma separated list of class names.  A new instance will be
 * created for each named class.  The default constructor of each class
 * may execute arbitrary code to update the logging configuration, such as
 * setting logger levels, adding handlers, adding filters, etc.
 * </ul>
 * <p>
 * Note that all classes loaded during LogManager configuration are
 * first searched on the system class path before any user class path.
 * That includes the LogManager class, any config classes, and any
 * handler classes.
 * <p>
 * Loggers are organized into a naming hierarchy based on their
 * dot separated names.  Thus "a.b.c" is a child of "a.b", but
 * "a.b1" and a.b2" are peers.
 * <p>
 * All properties whose names end with ".level" are assumed to define
 * log levels for Loggers.  Thus "foo.level" defines a log level for
 * the logger called "foo" and (recursively) for any of its children
 * in the naming hierarchy.  Log Levels are applied in the order they
 * are defined in the properties file.  Thus level settings for child
 * nodes in the tree should come after settings for their parents.
 * The property name ".level" can be used to set the level for the
 * root of the tree.
 * <p>
 * All methods on the LogManager object are multi-thread safe.
 *
 * @since 1.4
*/

public class LogManager {
    // The global LogManager object
    private static LogManager manager;

    private Properties props = new Properties();
    private final static Level defaultLevel = Level.INFO;

152 153
    // The map of the registered listeners. The map value is the registration
    // count to allow for cases where the same listener is registered many times.
154
    private final Map<Object,Integer> listenerMap = new HashMap<>();
155

M
mchung 已提交
156 157
    // LoggerContext for system loggers and user loggers
    private final LoggerContext systemContext = new SystemLoggerContext();
158
    private final LoggerContext userContext = new LoggerContext();
D
duke 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    private Logger rootLogger;

    // Have we done the primordial reading of the configuration file?
    // (Must be done after a suitable amount of java.lang.System
    // initialization has been done)
    private volatile boolean readPrimordialConfiguration;
    // Have we initialized global (root) handlers yet?
    // This gets set to false in readConfiguration
    private boolean initializedGlobalHandlers = true;
    // True if JVM death is imminent and the exit hook has been called.
    private boolean deathImminent;

    static {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
                public Object run() {
                    String cname = null;
                    try {
                        cname = System.getProperty("java.util.logging.manager");
                        if (cname != null) {
                            try {
179
                                Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(cname);
D
duke 已提交
180 181
                                manager = (LogManager) clz.newInstance();
                            } catch (ClassNotFoundException ex) {
182
                                Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(cname);
D
duke 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196
                                manager = (LogManager) clz.newInstance();
                            }
                        }
                    } catch (Exception ex) {
                        System.err.println("Could not load Logmanager \"" + cname + "\"");
                        ex.printStackTrace();
                    }
                    if (manager == null) {
                        manager = new LogManager();
                    }

                    // Create and retain Logger for the root of the namespace.
                    manager.rootLogger = manager.new RootLogger();
                    manager.addLogger(manager.rootLogger);
197
                    manager.systemContext.addLocalLogger(manager.rootLogger);
D
duke 已提交
198 199 200

                    // Adding the global Logger. Doing so in the Logger.<clinit>
                    // would deadlock with the LogManager.<clinit>.
201 202
                    Logger.global.setLogManager(manager);
                    manager.addLogger(Logger.global);
D
duke 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215

                    // We don't call readConfiguration() here, as we may be running
                    // very early in the JVM startup sequence.  Instead readConfiguration
                    // will be called lazily in getLogManager().
                    return null;
                }
            });
    }


    // This private class is used as a shutdown hook.
    // It does a "reset" to close all open handlers.
    private class Cleaner extends Thread {
216 217 218 219 220 221 222 223

        private Cleaner() {
            /* Set context class loader to null in order to avoid
             * keeping a strong reference to an application classloader.
             */
            this.setContextClassLoader(null);
        }

D
duke 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
        public void run() {
            // This is to ensure the LogManager.<clinit> is completed
            // before synchronized block. Otherwise deadlocks are possible.
            LogManager mgr = manager;

            // If the global handlers haven't been initialized yet, we
            // don't want to initialize them just so we can close them!
            synchronized (LogManager.this) {
                // Note that death is imminent.
                deathImminent = true;
                initializedGlobalHandlers = true;
            }

            // Do a reset to close all active handlers.
            reset();
        }
    }


    /**
     * Protected constructor.  This is protected so that container applications
     * (such as J2EE containers) can subclass the object.  It is non-public as
     * it is intended that there only be one LogManager object, whose value is
247
     * retrieved by calling LogManager.getLogManager.
D
duke 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
     */
    protected LogManager() {
        // Add a shutdown hook to close the global handlers.
        try {
            Runtime.getRuntime().addShutdownHook(new Cleaner());
        } catch (IllegalStateException e) {
            // If the VM is already shutting down,
            // We do not need to register shutdownHook.
        }
    }

    /**
     * Return the global LogManager object.
     */
    public static LogManager getLogManager() {
        if (manager != null) {
            manager.readPrimordialConfiguration();
        }
        return manager;
    }

    private void readPrimordialConfiguration() {
        if (!readPrimordialConfiguration) {
            synchronized (this) {
                if (!readPrimordialConfiguration) {
                    // If System.in/out/err are null, it's a good
                    // indication that we're still in the
                    // bootstrapping phase
                    if (System.out == null) {
                        return;
                    }
                    readPrimordialConfiguration = true;
M
mchung 已提交
280

D
duke 已提交
281
                    try {
M
mchung 已提交
282 283
                        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
                                public Void run() throws Exception {
D
duke 已提交
284
                                    readConfiguration();
285 286 287

                                    // Platform loggers begin to delegate to java.util.logging.Logger
                                    sun.util.logging.PlatformLogger.redirectPlatformLoggers();
D
duke 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
                                    return null;
                                }
                            });
                    } catch (Exception ex) {
                        // System.err.println("Can't read logging configuration:");
                        // ex.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * Adds an event listener to be invoked when the logging
     * properties are re-read. Adding multiple instances of
     * the same event Listener results in multiple entries
     * in the property event listener table.
     *
306 307 308 309
     * <p><b>WARNING:</b> This method is omitted from this class in all subset
     * Profiles of Java SE that do not include the {@code java.beans} package.
     * </p>
     *
D
duke 已提交
310 311 312 313
     * @param l  event listener
     * @exception  SecurityException  if a security manager exists and if
     *             the caller does not have LoggingPermission("control").
     * @exception NullPointerException if the PropertyChangeListener is null.
314 315 316 317 318 319
     * @deprecated The dependency on {@code PropertyChangeListener} creates a
     *             significant impediment to future modularization of the Java
     *             platform. This method will be removed in a future release.
     *             The global {@code LogManager} can detect changes to the
     *             logging configuration by overridding the {@link
     *             #readConfiguration readConfiguration} method.
D
duke 已提交
320
     */
321
    @Deprecated
D
duke 已提交
322
    public void addPropertyChangeListener(PropertyChangeListener l) throws SecurityException {
323
        PropertyChangeListener listener = Objects.requireNonNull(l);
324
        checkPermission();
325 326 327 328 329 330
        synchronized (listenerMap) {
            // increment the registration count if already registered
            Integer value = listenerMap.get(listener);
            value = (value == null) ? 1 : (value + 1);
            listenerMap.put(listener, value);
        }
D
duke 已提交
331 332 333 334 335 336 337 338 339 340 341 342
    }

    /**
     * Removes an event listener for property change events.
     * If the same listener instance has been added to the listener table
     * through multiple invocations of <CODE>addPropertyChangeListener</CODE>,
     * then an equivalent number of
     * <CODE>removePropertyChangeListener</CODE> invocations are required to remove
     * all instances of that listener from the listener table.
     * <P>
     * Returns silently if the given listener is not found.
     *
343 344 345 346
     * <p><b>WARNING:</b> This method is omitted from this class in all subset
     * Profiles of Java SE that do not include the {@code java.beans} package.
     * </p>
     *
D
duke 已提交
347 348 349
     * @param l  event listener (can be null)
     * @exception  SecurityException  if a security manager exists and if
     *             the caller does not have LoggingPermission("control").
350 351 352 353 354 355
     * @deprecated The dependency on {@code PropertyChangeListener} creates a
     *             significant impediment to future modularization of the Java
     *             platform. This method will be removed in a future release.
     *             The global {@code LogManager} can detect changes to the
     *             logging configuration by overridding the {@link
     *             #readConfiguration readConfiguration} method.
D
duke 已提交
356
     */
357
    @Deprecated
D
duke 已提交
358
    public void removePropertyChangeListener(PropertyChangeListener l) throws SecurityException {
359
        checkPermission();
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
        if (l != null) {
            PropertyChangeListener listener = l;
            synchronized (listenerMap) {
                Integer value = listenerMap.get(listener);
                if (value != null) {
                    // remove from map if registration count is 1, otherwise
                    // just decrement its count
                    int i = value.intValue();
                    if (i == 1) {
                        listenerMap.remove(listener);
                    } else {
                        assert i > 1;
                        listenerMap.put(listener, i - 1);
                    }
                }
            }
        }
D
duke 已提交
377 378
    }

M
mchung 已提交
379 380
    // Returns the LoggerContext for the user code (i.e. application or AppContext).
    // Loggers are isolated from each AppContext.
381
    private LoggerContext getUserContext() {
M
mchung 已提交
382
        LoggerContext context = null;
383

M
mchung 已提交
384 385 386 387 388 389 390 391 392 393
        SecurityManager sm = System.getSecurityManager();
        JavaAWTAccess javaAwtAccess = SharedSecrets.getJavaAWTAccess();
        if (sm != null && javaAwtAccess != null) {
            synchronized (javaAwtAccess) {
                // AppContext.getAppContext() returns the system AppContext if called
                // from a system thread but Logger.getLogger might be called from
                // an applet code. Instead, find the AppContext of the applet code
                // from the execution stack.
                Object ecx = javaAwtAccess.getExecutionContext();
                if (ecx == null) {
394
                    // fall back to thread group seach of AppContext
M
mchung 已提交
395 396
                    ecx = javaAwtAccess.getContext();
                }
397 398 399 400 401 402 403 404 405
                if (ecx != null) {
                    context = (LoggerContext)javaAwtAccess.get(ecx, LoggerContext.class);
                    if (context == null) {
                        if (javaAwtAccess.isMainAppContext()) {
                            context = userContext;
                        } else {
                            context = new LoggerContext();
                        }
                        javaAwtAccess.put(ecx, LoggerContext.class, context);
M
mchung 已提交
406 407 408
                    }
                }
            }
D
duke 已提交
409
        }
410
        return context != null ? context : userContext;
D
duke 已提交
411 412
    }

M
mchung 已提交
413 414 415 416 417 418 419
    private List<LoggerContext> contexts() {
        List<LoggerContext> cxs = new ArrayList<>();
        cxs.add(systemContext);
        cxs.add(getUserContext());
        return cxs;
    }

D
duke 已提交
420 421 422 423
    // Find or create a specified logger instance. If a logger has
    // already been created with the given name it is returned.
    // Otherwise a new logger instance is created and registered
    // in the LogManager global namespace.
424 425 426
    // This method will always return a non-null Logger object.
    // Synchronization is not required here. All synchronization for
    // adding a new Logger object is handled by addLogger().
427 428 429 430 431
    //
    // This method must delegate to the LogManager implementation to
    // add a new Logger or return the one that has been added previously
    // as a LogManager subclass may override the addLogger, getLogger,
    // readConfiguration, and other methods.
432
    Logger demandLogger(String name, String resourceBundleName, Class<?> caller) {
D
duke 已提交
433 434
        Logger result = getLogger(name);
        if (result == null) {
435
            // only allocate the new logger once
436
            Logger newLogger = new Logger(name, resourceBundleName, caller);
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
            do {
                if (addLogger(newLogger)) {
                    // We successfully added the new Logger that we
                    // created above so return it without refetching.
                    return newLogger;
                }

                // We didn't add the new Logger that we created above
                // because another thread added a Logger with the same
                // name after our null check above and before our call
                // to addLogger(). We have to refetch the Logger because
                // addLogger() returns a boolean instead of the Logger
                // reference itself. However, if the thread that created
                // the other Logger is not holding a strong reference to
                // the other Logger, then it is possible for the other
                // Logger to be GC'ed after we saw it in addLogger() and
                // before we can refetch it. If it has been GC'ed then
                // we'll just loop around and try again.
                result = getLogger(name);
            } while (result == null);
D
duke 已提交
457 458 459 460
        }
        return result;
    }

461
    Logger demandSystemLogger(String name, String resourceBundleName) {
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
        // Add a system logger in the system context's namespace
        final Logger sysLogger = systemContext.demandLogger(name, resourceBundleName);

        // Add the system logger to the LogManager's namespace if not exist
        // so that there is only one single logger of the given name.
        // System loggers are visible to applications unless a logger of
        // the same name has been added.
        Logger logger;
        do {
            // First attempt to call addLogger instead of getLogger
            // This would avoid potential bug in custom LogManager.getLogger
            // implementation that adds a logger if does not exist
            if (addLogger(sysLogger)) {
                // successfully added the new system logger
                logger = sysLogger;
            } else {
                logger = getLogger(name);
            }
        } while (logger == null);

        // LogManager will set the sysLogger's handlers via LogManager.addLogger method.
        if (logger != sysLogger && sysLogger.getHandlers().length == 0) {
            // if logger already exists but handlers not set
            final Logger l = logger;
            AccessController.doPrivileged(new PrivilegedAction<Void>() {
                public Void run() {
                    for (Handler hdl : l.getHandlers()) {
                        sysLogger.addHandler(hdl);
                    }
                    return null;
                }
            });
        }
        return sysLogger;
496 497 498 499 500 501 502 503 504
    }

    // LoggerContext maintains the logger namespace per context.
    // The default LogManager implementation has one system context and user
    // context.  The system context is used to maintain the namespace for
    // all system loggers and is queried by the system code.  If a system logger
    // doesn't exist in the user context, it'll also be added to the user context.
    // The user context is queried by the user code and all other loggers are
    // added in the user context.
M
mchung 已提交
505 506 507 508 509 510 511 512 513 514
    static class LoggerContext {
        // Table of named Loggers that maps names to Loggers.
        private final Hashtable<String,LoggerWeakRef> namedLoggers = new Hashtable<>();
        // Tree of named Loggers
        private final LogNode root;

        private LoggerContext() {
            this.root = new LogNode(null, this);
        }

515 516 517
        Logger demandLogger(String name, String resourceBundleName) {
            // a LogManager subclass may have its own implementation to add and
            // get a Logger.  So delegate to the LogManager to do the work.
518
            return manager.demandLogger(name, resourceBundleName, null);
519 520
        }

M
mchung 已提交
521 522 523 524 525 526 527 528 529 530 531 532 533 534
        synchronized Logger findLogger(String name) {
            LoggerWeakRef ref = namedLoggers.get(name);
            if (ref == null) {
                return null;
            }
            Logger logger = ref.get();
            if (logger == null) {
                // Hashtable holds stale weak reference
                // to a logger which has been GC-ed.
                removeLogger(name);
            }
            return logger;
        }

535
        synchronized void ensureRootLogger(Logger logger) {
536
            if (logger.getName().isEmpty())
537 538 539 540 541 542 543 544 545
                return;

            // during initialization, rootLogger is null when
            // instantiating itself RootLogger
            if (findLogger("") == null && manager.rootLogger != null) {
                addLocalLogger(manager.rootLogger);
            }
        }

546 547 548
        // Add a logger to this context.  This method will only set its level
        // and process parent loggers.  It doesn't set its handlers.
        synchronized boolean addLocalLogger(Logger logger) {
549 550
            ensureRootLogger(logger);

M
mchung 已提交
551 552 553 554 555 556 557
            final String name = logger.getName();
            if (name == null) {
                throw new NullPointerException();
            }
            LoggerWeakRef ref = namedLoggers.get(name);
            if (ref != null) {
                if (ref.get() == null) {
J
jgish 已提交
558
                    // It's possible that the Logger was GC'ed after a
M
mchung 已提交
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
                    // drainLoggerRefQueueBounded() call above so allow
                    // a new one to be registered.
                    removeLogger(name);
                } else {
                    // We already have a registered logger with the given name.
                    return false;
                }
            }

            // We're adding a new logger.
            // Note that we are creating a weak reference here.
            ref = manager.new LoggerWeakRef(logger);
            namedLoggers.put(name, ref);

            // Apply any initial level defined for the new logger.
            Level level = manager.getLevelProperty(name + ".level", null);
            if (level != null) {
                doSetLevel(logger, level);
            }

579 580 581
            // instantiation of the handler is done in the LogManager.addLogger
            // implementation as a handler class may be only visible to LogManager
            // subclass for the custom log manager case
M
mchung 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
            processParentHandlers(logger, name);

            // Find the new node and its parent.
            LogNode node = getNode(name);
            node.loggerRef = ref;
            Logger parent = null;
            LogNode nodep = node.parent;
            while (nodep != null) {
                LoggerWeakRef nodeRef = nodep.loggerRef;
                if (nodeRef != null) {
                    parent = nodeRef.get();
                    if (parent != null) {
                        break;
                    }
                }
                nodep = nodep.parent;
            }

            if (parent != null) {
                doSetParent(logger, parent);
            }
            // Walk over the children and tell them we are their new parent.
            node.walkAndSetParent(logger);
            // new LogNode is ready so tell the LoggerWeakRef about it
            ref.setNode(node);
            return true;
        }

J
jgish 已提交
610 611
        // note: all calls to removeLogger are synchronized on LogManager's
        // intrinsic lock
M
mchung 已提交
612 613 614 615 616 617 618 619 620 621
        void removeLogger(String name) {
            namedLoggers.remove(name);
        }

        synchronized Enumeration<String> getLoggerNames() {
            return namedLoggers.keys();
        }

        // If logger.getUseParentHandlers() returns 'true' and any of the logger's
        // parents have levels or handlers defined, make sure they are instantiated.
622 623 624 625 626 627 628 629 630 631 632 633 634
        private void processParentHandlers(final Logger logger, final String name) {
            AccessController.doPrivileged(new PrivilegedAction<Void>() {
                public Void run() {
                    if (logger != manager.rootLogger) {
                        boolean useParent = manager.getBooleanProperty(name + ".useParentHandlers", true);
                        if (!useParent) {
                            logger.setUseParentHandlers(false);
                        }
                    }
                    return null;
                }
            });

M
mchung 已提交
635 636 637 638 639 640 641 642 643 644 645
            int ix = 1;
            for (;;) {
                int ix2 = name.indexOf(".", ix);
                if (ix2 < 0) {
                    break;
                }
                String pname = name.substring(0, ix2);
                if (manager.getProperty(pname + ".level") != null ||
                    manager.getProperty(pname + ".handlers") != null) {
                    // This pname has a level/handlers definition.
                    // Make sure it exists.
646
                    demandLogger(pname, null);
M
mchung 已提交
647 648
                }
                ix = ix2+1;
D
duke 已提交
649
            }
M
mchung 已提交
650
        }
D
duke 已提交
651

M
mchung 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
        // Gets a node in our tree of logger nodes.
        // If necessary, create it.
        LogNode getNode(String name) {
            if (name == null || name.equals("")) {
                return root;
            }
            LogNode node = root;
            while (name.length() > 0) {
                int ix = name.indexOf(".");
                String head;
                if (ix > 0) {
                    head = name.substring(0, ix);
                    name = name.substring(ix + 1);
                } else {
                    head = name;
                    name = "";
                }
                if (node.children == null) {
                    node.children = new HashMap<>();
                }
                LogNode child = node.children.get(head);
                if (child == null) {
                    child = new LogNode(node, this);
                    node.children.put(head, child);
                }
                node = child;
D
duke 已提交
678
            }
M
mchung 已提交
679 680 681 682 683
            return node;
        }
    }

    static class SystemLoggerContext extends LoggerContext {
684 685 686 687
        // Add a system logger in the system context's namespace as well as
        // in the LogManager's namespace if not exist so that there is only
        // one single logger of the given name.  System loggers are visible
        // to applications unless a logger of the same name has been added.
M
mchung 已提交
688 689 690
        Logger demandLogger(String name, String resourceBundleName) {
            Logger result = findLogger(name);
            if (result == null) {
691 692
                // only allocate the new system logger once
                Logger newLogger = new Logger(name, resourceBundleName);
M
mchung 已提交
693
                do {
694
                    if (addLocalLogger(newLogger)) {
M
mchung 已提交
695 696
                        // We successfully added the new Logger that we
                        // created above so return it without refetching.
697 698 699 700 701 702 703 704 705 706 707 708 709 710
                        result = newLogger;
                    } else {
                        // We didn't add the new Logger that we created above
                        // because another thread added a Logger with the same
                        // name after our null check above and before our call
                        // to addLogger(). We have to refetch the Logger because
                        // addLogger() returns a boolean instead of the Logger
                        // reference itself. However, if the thread that created
                        // the other Logger is not holding a strong reference to
                        // the other Logger, then it is possible for the other
                        // Logger to be GC'ed after we saw it in addLogger() and
                        // before we can refetch it. If it has been GC'ed then
                        // we'll just loop around and try again.
                        result = findLogger(name);
M
mchung 已提交
711 712
                    }
                } while (result == null);
D
duke 已提交
713
            }
M
mchung 已提交
714
            return result;
D
duke 已提交
715 716 717 718 719 720 721 722
        }
    }

    // Add new per logger handlers.
    // We need to raise privilege here. All our decisions will
    // be made based on the logging configuration, which can
    // only be modified by trusted code.
    private void loadLoggerHandlers(final Logger logger, final String name,
723 724
                                    final String handlersPropertyName)
    {
D
duke 已提交
725 726 727 728 729 730
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                String names[] = parseClassNames(handlersPropertyName);
                for (int i = 0; i < names.length; i++) {
                    String word = names[i];
                    try {
731
                        Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word);
732
                        Handler hdl = (Handler) clz.newInstance();
M
mchung 已提交
733 734 735 736 737 738 739 740 741 742
                        // Check if there is a property defining the
                        // this handler's level.
                        String levs = getProperty(word + ".level");
                        if (levs != null) {
                            Level l = Level.findLevel(levs);
                            if (l != null) {
                                hdl.setLevel(l);
                            } else {
                                // Probably a bad level. Drop through.
                                System.err.println("Can't set level for " + word);
D
duke 已提交
743 744 745 746 747 748 749 750 751 752 753
                            }
                        }
                        // Add this Handler to the logger
                        logger.addHandler(hdl);
                    } catch (Exception ex) {
                        System.err.println("Can't load log handler \"" + word + "\"");
                        System.err.println("" + ex);
                        ex.printStackTrace();
                    }
                }
                return null;
754 755
            }
        });
D
duke 已提交
756 757
    }

758 759 760 761

    // loggerRefQueue holds LoggerWeakRef objects for Logger objects
    // that have been GC'ed.
    private final ReferenceQueue<Logger> loggerRefQueue
762
        = new ReferenceQueue<>();
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799

    // Package-level inner class.
    // Helper class for managing WeakReferences to Logger objects.
    //
    // LogManager.namedLoggers
    //     - has weak references to all named Loggers
    //     - namedLoggers keeps the LoggerWeakRef objects for the named
    //       Loggers around until we can deal with the book keeping for
    //       the named Logger that is being GC'ed.
    // LogManager.LogNode.loggerRef
    //     - has a weak reference to a named Logger
    //     - the LogNode will also keep the LoggerWeakRef objects for
    //       the named Loggers around; currently LogNodes never go away.
    // Logger.kids
    //     - has a weak reference to each direct child Logger; this
    //       includes anonymous and named Loggers
    //     - anonymous Loggers are always children of the rootLogger
    //       which is a strong reference; rootLogger.kids keeps the
    //       LoggerWeakRef objects for the anonymous Loggers around
    //       until we can deal with the book keeping.
    //
    final class LoggerWeakRef extends WeakReference<Logger> {
        private String                name;       // for namedLoggers cleanup
        private LogNode               node;       // for loggerRef cleanup
        private WeakReference<Logger> parentRef;  // for kids cleanup

        LoggerWeakRef(Logger logger) {
            super(logger, loggerRefQueue);

            name = logger.getName();  // save for namedLoggers cleanup
        }

        // dispose of this LoggerWeakRef object
        void dispose() {
            if (node != null) {
                // if we have a LogNode, then we were a named Logger
                // so clear namedLoggers weak ref to us
M
mchung 已提交
800
                node.context.removeLogger(name);
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
                name = null;  // clear our ref to the Logger's name

                node.loggerRef = null;  // clear LogNode's weak ref to us
                node = null;            // clear our ref to LogNode
            }

            if (parentRef != null) {
                // this LoggerWeakRef has or had a parent Logger
                Logger parent = parentRef.get();
                if (parent != null) {
                    // the parent Logger is still there so clear the
                    // parent Logger's weak ref to us
                    parent.removeChildLogger(this);
                }
                parentRef = null;  // clear our weak ref to the parent Logger
            }
        }

        // set the node field to the specified value
        void setNode(LogNode node) {
            this.node = node;
        }

        // set the parentRef field to the specified value
        void setParentRef(WeakReference<Logger> parentRef) {
            this.parentRef = parentRef;
        }
    }

    // Package-level method.
    // Drain some Logger objects that have been GC'ed.
    //
    // drainLoggerRefQueueBounded() is called by addLogger() below
    // and by Logger.getAnonymousLogger(String) so we'll drain up to
    // MAX_ITERATIONS GC'ed Loggers for every Logger we add.
    //
    // On a WinXP VMware client, a MAX_ITERATIONS value of 400 gives
    // us about a 50/50 mix in increased weak ref counts versus
    // decreased weak ref counts in the AnonLoggerWeakRefLeak test.
    // Here are stats for cleaning up sets of 400 anonymous Loggers:
    //   - test duration 1 minute
    //   - sample size of 125 sets of 400
    //   - average: 1.99 ms
    //   - minimum: 0.57 ms
    //   - maximum: 25.3 ms
    //
    // The same config gives us a better decreased weak ref count
    // than increased weak ref count in the LoggerWeakRefLeak test.
    // Here are stats for cleaning up sets of 400 named Loggers:
    //   - test duration 2 minutes
    //   - sample size of 506 sets of 400
    //   - average: 0.57 ms
    //   - minimum: 0.02 ms
    //   - maximum: 10.9 ms
    //
    private final static int MAX_ITERATIONS = 400;
    final synchronized void drainLoggerRefQueueBounded() {
        for (int i = 0; i < MAX_ITERATIONS; i++) {
            if (loggerRefQueue == null) {
                // haven't finished loading LogManager yet
                break;
            }

            LoggerWeakRef ref = (LoggerWeakRef) loggerRefQueue.poll();
            if (ref == null) {
                break;
            }
            // a Logger object has been GC'ed so clean it up
            ref.dispose();
        }
    }

D
duke 已提交
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
    /**
     * Add a named logger.  This does nothing and returns false if a logger
     * with the same name is already registered.
     * <p>
     * The Logger factory methods call this method to register each
     * newly created Logger.
     * <p>
     * The application should retain its own reference to the Logger
     * object to avoid it being garbage collected.  The LogManager
     * may only retain a weak reference.
     *
     * @param   logger the new logger.
     * @return  true if the argument logger was registered successfully,
     *          false if a logger of that name already exists.
     * @exception NullPointerException if the logger name is null.
     */
M
mchung 已提交
889
    public boolean addLogger(Logger logger) {
D
duke 已提交
890 891 892 893
        final String name = logger.getName();
        if (name == null) {
            throw new NullPointerException();
        }
J
jgish 已提交
894
        drainLoggerRefQueueBounded();
895 896 897 898 899 900 901
        LoggerContext cx = getUserContext();
        if (cx.addLocalLogger(logger)) {
            // Do we have a per logger handler too?
            // Note: this will add a 200ms penalty
            loadLoggerHandlers(logger, name, name + ".handlers");
            return true;
        } else {
M
mchung 已提交
902
            return false;
D
duke 已提交
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
        }
    }

    // Private method to set a level on a logger.
    // If necessary, we raise privilege before doing the call.
    private static void doSetLevel(final Logger logger, final Level level) {
        SecurityManager sm = System.getSecurityManager();
        if (sm == null) {
            // There is no security manager, so things are easy.
            logger.setLevel(level);
            return;
        }
        // There is a security manager.  Raise privilege before
        // calling setLevel.
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                logger.setLevel(level);
                return null;
            }});
    }

    // Private method to set a parent on a logger.
    // If necessary, we raise privilege before doing the setParent call.
    private static void doSetParent(final Logger logger, final Logger parent) {
        SecurityManager sm = System.getSecurityManager();
        if (sm == null) {
            // There is no security manager, so things are easy.
            logger.setParent(parent);
            return;
        }
        // There is a security manager.  Raise privilege before
        // calling setParent.
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                logger.setParent(parent);
                return null;
            }});
    }

    /**
     * Method to find a named logger.
     * <p>
     * Note that since untrusted code may create loggers with
     * arbitrary names this method should not be relied on to
     * find Loggers for security sensitive logging.
948 949 950 951 952
     * It is also important to note that the Logger associated with the
     * String {@code name} may be garbage collected at any time if there
     * is no strong reference to the Logger. The caller of this method
     * must check the return value for null in order to properly handle
     * the case where the Logger has been garbage collected.
D
duke 已提交
953 954 955 956
     * <p>
     * @param name name of the logger
     * @return  matching logger or null if none is found
     */
M
mchung 已提交
957
    public Logger getLogger(String name) {
958
        return getUserContext().findLogger(name);
D
duke 已提交
959 960 961 962 963 964 965
    }

    /**
     * Get an enumeration of known logger names.
     * <p>
     * Note:  Loggers may be added dynamically as new classes are loaded.
     * This method only reports on the loggers that are currently registered.
966 967 968 969 970 971 972 973
     * It is also important to note that this method only returns the name
     * of a Logger, not a strong reference to the Logger itself.
     * The returned String does nothing to prevent the Logger from being
     * garbage collected. In particular, if the returned name is passed
     * to {@code LogManager.getLogger()}, then the caller must check the
     * return value from {@code LogManager.getLogger()} for null to properly
     * handle the case where the Logger has been garbage collected in the
     * time since its name was returned by this method.
D
duke 已提交
974 975 976
     * <p>
     * @return  enumeration of logger name strings
     */
M
mchung 已提交
977
    public Enumeration<String> getLoggerNames() {
978
        return getUserContext().getLoggerNames();
D
duke 已提交
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
    }

    /**
     * Reinitialize the logging properties and reread the logging configuration.
     * <p>
     * The same rules are used for locating the configuration properties
     * as are used at startup.  So normally the logging properties will
     * be re-read from the same file that was used at startup.
     * <P>
     * Any log level definitions in the new configuration file will be
     * applied using Logger.setLevel(), if the target Logger exists.
     * <p>
     * A PropertyChangeEvent will be fired after the properties are read.
     *
     * @exception  SecurityException  if a security manager exists and if
     *             the caller does not have LoggingPermission("control").
     * @exception  IOException if there are IO problems reading the configuration.
     */
    public void readConfiguration() throws IOException, SecurityException {
998
        checkPermission();
D
duke 已提交
999 1000 1001 1002 1003 1004 1005 1006 1007

        // if a configuration class is specified, load it and use it.
        String cname = System.getProperty("java.util.logging.config.class");
        if (cname != null) {
            try {
                // Instantiate the named class.  It is its constructor's
                // responsibility to initialize the logging configuration, by
                // calling readConfiguration(InputStream) with a suitable stream.
                try {
1008
                    Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(cname);
D
duke 已提交
1009 1010 1011
                    clz.newInstance();
                    return;
                } catch (ClassNotFoundException ex) {
1012
                    Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(cname);
D
duke 已提交
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
                    clz.newInstance();
                    return;
                }
            } catch (Exception ex) {
                System.err.println("Logging configuration class \"" + cname + "\" failed");
                System.err.println("" + ex);
                // keep going and useful config file.
            }
        }

        String fname = System.getProperty("java.util.logging.config.file");
        if (fname == null) {
            fname = System.getProperty("java.home");
            if (fname == null) {
                throw new Error("Can't find java.home ??");
            }
            File f = new File(fname, "lib");
            f = new File(f, "logging.properties");
            fname = f.getCanonicalPath();
        }
        InputStream in = new FileInputStream(fname);
        BufferedInputStream bin = new BufferedInputStream(in);
        try {
            readConfiguration(bin);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    /**
     * Reset the logging configuration.
     * <p>
     * For all named loggers, the reset operation removes and closes
     * all Handlers and (except for the root logger) sets the level
     * to null.  The root logger's level is set to Level.INFO.
     *
     * @exception  SecurityException  if a security manager exists and if
     *             the caller does not have LoggingPermission("control").
     */

    public void reset() throws SecurityException {
1056
        checkPermission();
D
duke 已提交
1057 1058 1059 1060 1061 1062
        synchronized (this) {
            props = new Properties();
            // Since we are doing a reset we no longer want to initialize
            // the global handlers, if they haven't been initialized yet.
            initializedGlobalHandlers = true;
        }
M
mchung 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071
        for (LoggerContext cx : contexts()) {
            Enumeration<String> enum_ = cx.getLoggerNames();
            while (enum_.hasMoreElements()) {
                String name = enum_.nextElement();
                Logger logger = cx.findLogger(name);
                if (logger != null) {
                    resetLogger(logger);
                }
            }
D
duke 已提交
1072 1073 1074 1075
        }
    }

    // Private method to reset an individual target logger.
M
mchung 已提交
1076
    private void resetLogger(Logger logger) {
D
duke 已提交
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
        // Close all the Logger's handlers.
        Handler[] targets = logger.getHandlers();
        for (int i = 0; i < targets.length; i++) {
            Handler h = targets[i];
            logger.removeHandler(h);
            try {
                h.close();
            } catch (Exception ex) {
                // Problems closing a handler?  Keep going...
            }
        }
M
mchung 已提交
1088
        String name = logger.getName();
D
duke 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
        if (name != null && name.equals("")) {
            // This is the root logger.
            logger.setLevel(defaultLevel);
        } else {
            logger.setLevel(null);
        }
    }

    // get a list of whitespace separated classnames from a property.
    private String[] parseClassNames(String propertyName) {
        String hands = getProperty(propertyName);
        if (hands == null) {
            return new String[0];
        }
        hands = hands.trim();
        int ix = 0;
1105
        Vector<String> result = new Vector<>();
D
duke 已提交
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
        while (ix < hands.length()) {
            int end = ix;
            while (end < hands.length()) {
                if (Character.isWhitespace(hands.charAt(end))) {
                    break;
                }
                if (hands.charAt(end) == ',') {
                    break;
                }
                end++;
            }
            String word = hands.substring(ix, end);
            ix = end+1;
            word = word.trim();
            if (word.length() == 0) {
                continue;
            }
            result.add(word);
        }
        return result.toArray(new String[result.size()]);
    }

    /**
     * Reinitialize the logging properties and reread the logging configuration
     * from the given stream, which should be in java.util.Properties format.
     * A PropertyChangeEvent will be fired after the properties are read.
     * <p>
     * Any log level definitions in the new configuration file will be
     * applied using Logger.setLevel(), if the target Logger exists.
     *
     * @param ins       stream to read properties from
     * @exception  SecurityException  if a security manager exists and if
     *             the caller does not have LoggingPermission("control").
     * @exception  IOException if there are problems reading from the stream.
     */
    public void readConfiguration(InputStream ins) throws IOException, SecurityException {
1142
        checkPermission();
D
duke 已提交
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
        reset();

        // Load the properties
        props.load(ins);
        // Instantiate new configuration objects.
        String names[] = parseClassNames("config");

        for (int i = 0; i < names.length; i++) {
            String word = names[i];
            try {
1153
                Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word);
D
duke 已提交
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
                clz.newInstance();
            } catch (Exception ex) {
                System.err.println("Can't load config class \"" + word + "\"");
                System.err.println("" + ex);
                // ex.printStackTrace();
            }
        }

        // Set levels on any pre-existing loggers, based on the new properties.
        setLevelsOnExistingLoggers();

        // Notify any interested parties that our properties have changed.
1166 1167
        // We first take a copy of the listener map so that we aren't holding any
        // locks when calling the listeners.
1168
        Map<Object,Integer> listeners = null;
1169 1170 1171 1172 1173
        synchronized (listenerMap) {
            if (!listenerMap.isEmpty())
                listeners = new HashMap<>(listenerMap);
        }
        if (listeners != null) {
1174 1175 1176 1177
            assert Beans.isBeansPresent();
            Object ev = Beans.newPropertyChangeEvent(LogManager.class, null, null, null);
            for (Map.Entry<Object,Integer> entry : listeners.entrySet()) {
                Object listener = entry.getKey();
1178 1179
                int count = entry.getValue().intValue();
                for (int i = 0; i < count; i++) {
1180
                    Beans.invokePropertyChange(listener, ev);
1181 1182 1183
                }
            }
        }
D
duke 已提交
1184

1185

D
duke 已提交
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
        // Note that we need to reinitialize global handles when
        // they are first referenced.
        synchronized (this) {
            initializedGlobalHandlers = false;
        }
    }

    /**
     * Get the value of a logging property.
     * The method returns null if the property is not found.
     * @param name      property name
     * @return          property value
     */
    public String getProperty(String name) {
        return props.getProperty(name);
    }

    // Package private method to get a String property.
    // If the property is not defined we return the given
    // default value.
    String getStringProperty(String name, String defaultValue) {
        String val = getProperty(name);
        if (val == null) {
            return defaultValue;
        }
        return val.trim();
    }

    // Package private method to get an integer property.
    // If the property is not defined or cannot be parsed
    // we return the given default value.
    int getIntProperty(String name, int defaultValue) {
        String val = getProperty(name);
        if (val == null) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(val.trim());
        } catch (Exception ex) {
            return defaultValue;
        }
    }

    // Package private method to get a boolean property.
    // If the property is not defined or cannot be parsed
    // we return the given default value.
    boolean getBooleanProperty(String name, boolean defaultValue) {
        String val = getProperty(name);
        if (val == null) {
            return defaultValue;
        }
        val = val.toLowerCase();
        if (val.equals("true") || val.equals("1")) {
            return true;
        } else if (val.equals("false") || val.equals("0")) {
            return false;
        }
        return defaultValue;
    }

    // Package private method to get a Level property.
    // If the property is not defined or cannot be parsed
    // we return the given default value.
    Level getLevelProperty(String name, Level defaultValue) {
        String val = getProperty(name);
        if (val == null) {
            return defaultValue;
        }
M
mchung 已提交
1254 1255
        Level l = Level.findLevel(val.trim());
        return l != null ? l : defaultValue;
D
duke 已提交
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
    }

    // Package private method to get a filter property.
    // We return an instance of the class named by the "name"
    // property. If the property is not defined or has problems
    // we return the defaultValue.
    Filter getFilterProperty(String name, Filter defaultValue) {
        String val = getProperty(name);
        try {
            if (val != null) {
1266
                Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(val);
D
duke 已提交
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
                return (Filter) clz.newInstance();
            }
        } catch (Exception ex) {
            // We got one of a variety of exceptions in creating the
            // class or creating an instance.
            // Drop through.
        }
        // We got an exception.  Return the defaultValue.
        return defaultValue;
    }


    // Package private method to get a formatter property.
    // We return an instance of the class named by the "name"
    // property. If the property is not defined or has problems
    // we return the defaultValue.
    Formatter getFormatterProperty(String name, Formatter defaultValue) {
        String val = getProperty(name);
        try {
            if (val != null) {
1287
                Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(val);
D
duke 已提交
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
                return (Formatter) clz.newInstance();
            }
        } catch (Exception ex) {
            // We got one of a variety of exceptions in creating the
            // class or creating an instance.
            // Drop through.
        }
        // We got an exception.  Return the defaultValue.
        return defaultValue;
    }

    // Private method to load the global handlers.
    // We do the real work lazily, when the global handlers
    // are first used.
    private synchronized void initializeGlobalHandlers() {
        if (initializedGlobalHandlers) {
            return;
        }

        initializedGlobalHandlers = true;

        if (deathImminent) {
            // Aaargh...
            // The VM is shutting down and our exit hook has been called.
            // Avoid allocating global handlers.
            return;
        }
        loadLoggerHandlers(rootLogger, null, "handlers");
    }

1318
    private final Permission controlPermission = new LoggingPermission("control", null);
D
duke 已提交
1319

1320 1321 1322 1323 1324
    void checkPermission() {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null)
            sm.checkPermission(controlPermission);
    }
D
duke 已提交
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336

    /**
     * Check that the current context is trusted to modify the logging
     * configuration.  This requires LoggingPermission("control").
     * <p>
     * If the check fails we throw a SecurityException, otherwise
     * we return normally.
     *
     * @exception  SecurityException  if a security manager exists and if
     *             the caller does not have LoggingPermission("control").
     */
    public void checkAccess() throws SecurityException {
1337
        checkPermission();
D
duke 已提交
1338 1339 1340 1341 1342
    }

    // Nested class to represent a node in our tree of named loggers.
    private static class LogNode {
        HashMap<String,LogNode> children;
1343
        LoggerWeakRef loggerRef;
D
duke 已提交
1344
        LogNode parent;
M
mchung 已提交
1345
        final LoggerContext context;
D
duke 已提交
1346

M
mchung 已提交
1347
        LogNode(LogNode parent, LoggerContext context) {
D
duke 已提交
1348
            this.parent = parent;
M
mchung 已提交
1349
            this.context = context;
D
duke 已提交
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        }

        // Recursive method to walk the tree below a node and set
        // a new parent logger.
        void walkAndSetParent(Logger parent) {
            if (children == null) {
                return;
            }
            Iterator<LogNode> values = children.values().iterator();
            while (values.hasNext()) {
                LogNode node = values.next();
1361
                LoggerWeakRef ref = node.loggerRef;
D
duke 已提交
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
                Logger logger = (ref == null) ? null : ref.get();
                if (logger == null) {
                    node.walkAndSetParent(parent);
                } else {
                    doSetParent(logger, parent);
                }
            }
        }
    }

    // We use a subclass of Logger for the root logger, so
    // that we only instantiate the global handlers when they
    // are first needed.
    private class RootLogger extends Logger {
        private RootLogger() {
            super("", null);
            setLevel(defaultLevel);
        }

        public void log(LogRecord record) {
            // Make sure that the global handlers have been instantiated.
            initializeGlobalHandlers();
            super.log(record);
        }

        public void addHandler(Handler h) {
            initializeGlobalHandlers();
            super.addHandler(h);
        }

        public void removeHandler(Handler h) {
            initializeGlobalHandlers();
            super.removeHandler(h);
        }

        public Handler[] getHandlers() {
            initializeGlobalHandlers();
            return super.getHandlers();
        }
    }


    // Private method to be called when the configuration has
    // changed to apply any level settings to any pre-existing loggers.
    synchronized private void setLevelsOnExistingLoggers() {
1407
        Enumeration<?> enum_ = props.propertyNames();
D
duke 已提交
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
        while (enum_.hasMoreElements()) {
            String key = (String)enum_.nextElement();
            if (!key.endsWith(".level")) {
                // Not a level definition.
                continue;
            }
            int ix = key.length() - 6;
            String name = key.substring(0, ix);
            Level level = getLevelProperty(key, null);
            if (level == null) {
                System.err.println("Bad level value for property: " + key);
                continue;
            }
M
mchung 已提交
1421 1422 1423 1424 1425 1426
            for (LoggerContext cx : contexts()) {
                Logger l = cx.findLogger(name);
                if (l == null) {
                    continue;
                }
                l.setLevel(level);
D
duke 已提交
1427 1428 1429 1430 1431 1432 1433 1434
            }
        }
    }

    // Management Support
    private static LoggingMXBean loggingMXBean = null;
    /**
     * String representation of the
1435 1436 1437 1438 1439 1440
     * {@link javax.management.ObjectName} for the management interface
     * for the logging facility.
     *
     * @see java.lang.management.PlatformLoggingMXBean
     * @see java.util.logging.LoggingMXBean
     *
D
duke 已提交
1441 1442 1443 1444 1445 1446 1447
     * @since 1.5
     */
    public final static String LOGGING_MXBEAN_NAME
        = "java.util.logging:type=Logging";

    /**
     * Returns <tt>LoggingMXBean</tt> for managing loggers.
1448 1449 1450
     * An alternative way to manage loggers is through the
     * {@link java.lang.management.PlatformLoggingMXBean} interface
     * that can be obtained by calling:
1451
     * <pre>
1452 1453
     *     PlatformLoggingMXBean logging = {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
     *         ManagementFactory.getPlatformMXBean}(PlatformLoggingMXBean.class);
1454
     * </pre>
D
duke 已提交
1455 1456 1457
     *
     * @return a {@link LoggingMXBean} object.
     *
1458
     * @see java.lang.management.PlatformLoggingMXBean
D
duke 已提交
1459 1460
     * @since 1.5
     */
1461
    public static synchronized LoggingMXBean getLoggingMXBean() {
D
duke 已提交
1462 1463 1464 1465 1466 1467
        if (loggingMXBean == null) {
            loggingMXBean =  new Logging();
        }
        return loggingMXBean;
    }

1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
    /**
     * A class that provides access to the java.beans.PropertyChangeListener
     * and java.beans.PropertyChangeEvent without creating a static dependency
     * on java.beans. This class can be removed once the addPropertyChangeListener
     * and removePropertyChangeListener methods are removed.
     */
    private static class Beans {
        private static final Class<?> propertyChangeListenerClass =
            getClass("java.beans.PropertyChangeListener");

        private static final Class<?> propertyChangeEventClass =
            getClass("java.beans.PropertyChangeEvent");

        private static final Method propertyChangeMethod =
            getMethod(propertyChangeListenerClass,
                      "propertyChange",
                      propertyChangeEventClass);

        private static final Constructor<?> propertyEventCtor =
            getConstructor(propertyChangeEventClass,
                           Object.class,
                           String.class,
                           Object.class,
                           Object.class);

        private static Class<?> getClass(String name) {
            try {
                return Class.forName(name, true, Beans.class.getClassLoader());
            } catch (ClassNotFoundException e) {
                return null;
            }
        }
        private static Constructor<?> getConstructor(Class<?> c, Class<?>... types) {
            try {
                return (c == null) ? null : c.getDeclaredConstructor(types);
            } catch (NoSuchMethodException x) {
                throw new AssertionError(x);
            }
        }

        private static Method getMethod(Class<?> c, String name, Class<?>... types) {
            try {
                return (c == null) ? null : c.getMethod(name, types);
            } catch (NoSuchMethodException e) {
                throw new AssertionError(e);
            }
        }

        /**
         * Returns {@code true} if java.beans is present.
         */
        static boolean isBeansPresent() {
            return propertyChangeListenerClass != null &&
                   propertyChangeEventClass != null;
        }

        /**
         * Returns a new PropertyChangeEvent with the given source, property
         * name, old and new values.
         */
        static Object newPropertyChangeEvent(Object source, String prop,
                                             Object oldValue, Object newValue)
        {
            try {
                return propertyEventCtor.newInstance(source, prop, oldValue, newValue);
            } catch (InstantiationException | IllegalAccessException x) {
                throw new AssertionError(x);
            } catch (InvocationTargetException x) {
                Throwable cause = x.getCause();
                if (cause instanceof Error)
                    throw (Error)cause;
                if (cause instanceof RuntimeException)
                    throw (RuntimeException)cause;
                throw new AssertionError(x);
            }
        }

        /**
         * Invokes the given PropertyChangeListener's propertyChange method
         * with the given event.
         */
        static void invokePropertyChange(Object listener, Object ev) {
            try {
                propertyChangeMethod.invoke(listener, ev);
            } catch (IllegalAccessException x) {
                throw new AssertionError(x);
            } catch (InvocationTargetException x) {
                Throwable cause = x.getCause();
                if (cause instanceof Error)
                    throw (Error)cause;
                if (cause instanceof RuntimeException)
                    throw (RuntimeException)cause;
                throw new AssertionError(x);
            }
        }
    }
D
duke 已提交
1564
}