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.lang.ref.WeakReference;
  30 import java.security.AccessController;
  31 import java.security.PrivilegedAction;
  32 import java.util.ArrayList;
  33 import java.util.Iterator;
  34 import java.util.Locale;
  35 import java.util.MissingResourceException;
  36 import java.util.ResourceBundle;
  37 import java.util.concurrent.CopyOnWriteArrayList;
  38 import java.util.function.Supplier;
  39 import sun.reflect.CallerSensitive;
  40 import sun.reflect.Reflection;
  41 
  42 /**
  43  * A Logger object is used to log messages for a specific
  44  * system or application component.  Loggers are normally named,
  45  * using a hierarchical dot-separated namespace.  Logger names
  46  * can be arbitrary strings, but they should normally be based on
  47  * the package name or class name of the logged component, such
  48  * as java.net or javax.swing.  In addition it is possible to create
  49  * "anonymous" Loggers that are not stored in the Logger namespace.
  50  * <p>
  51  * Logger objects may be obtained by calls on one of the getLogger
  52  * factory methods.  These will either create a new Logger or
  53  * return a suitable existing Logger. It is important to note that
  54  * the Logger returned by one of the {@code getLogger} factory methods
  55  * may be garbage collected at any time if a strong reference to the
  56  * Logger is not kept.
  57  * <p>
  58  * Logging messages will be forwarded to registered Handler
  59  * objects, which can forward the messages to a variety of
  60  * destinations, including consoles, files, OS logs, etc.
  61  * <p>
  62  * Each Logger keeps track of a "parent" Logger, which is its
  63  * nearest existing ancestor in the Logger namespace.
  64  * <p>
  65  * Each Logger has a "Level" associated with it.  This reflects
  66  * a minimum Level that this logger cares about.  If a Logger's
  67  * level is set to <tt>null</tt>, then its effective level is inherited
  68  * from its parent, which may in turn obtain it recursively from its
  69  * parent, and so on up the tree.
  70  * <p>
  71  * The log level can be configured based on the properties from the
  72  * logging configuration file, as described in the description
  73  * of the LogManager class.  However it may also be dynamically changed
  74  * by calls on the Logger.setLevel method.  If a logger's level is
  75  * changed the change may also affect child loggers, since any child
  76  * logger that has <tt>null</tt> as its level will inherit its
  77  * effective level from its parent.
  78  * <p>
  79  * On each logging call the Logger initially performs a cheap
  80  * check of the request level (e.g., SEVERE or FINE) against the
  81  * effective log level of the logger.  If the request level is
  82  * lower than the log level, the logging call returns immediately.
  83  * <p>
  84  * After passing this initial (cheap) test, the Logger will allocate
  85  * a LogRecord to describe the logging message.  It will then call a
  86  * Filter (if present) to do a more detailed check on whether the
  87  * record should be published.  If that passes it will then publish
  88  * the LogRecord to its output Handlers.  By default, loggers also
  89  * publish to their parent's Handlers, recursively up the tree.
  90  * <p>
  91  * Each Logger may have a ResourceBundle name associated with it.
  92  * The named bundle will be used for localizing logging messages.
  93  * If a Logger does not have its own ResourceBundle name, then
  94  * it will inherit the ResourceBundle name from its parent,
  95  * recursively up the tree.
  96  * <p>
  97  * Most of the logger output methods take a "msg" argument.  This
  98  * msg argument may be either a raw value or a localization key.
  99  * During formatting, if the logger has (or inherits) a localization
 100  * ResourceBundle and if the ResourceBundle has a mapping for the msg
 101  * string, then the msg string is replaced by the localized value.
 102  * Otherwise the original msg string is used.  Typically, formatters use
 103  * java.text.MessageFormat style formatting to format parameters, so
 104  * for example a format string "{0} {1}" would format two parameters
 105  * as strings.
 106  * <p>
 107  * A set of methods alternatively take a "msgSupplier" instead of a "msg"
 108  * argument.  These methods take a {@link Supplier}{@code <String>} function
 109  * which is invoked to construct the desired log message only when the message
 110  * actually is to be logged based on the effective log level thus eliminating
 111  * unnecessary message construction. For example, if the developer wants to
 112  * log system health status for diagnosis, with the String-accepting version,
 113  * the code would look like:
 114  <pre><code>
 115 
 116    class DiagnosisMessages {
 117      static String systemHealthStatus() {
 118        // collect system health information
 119        ...
 120      }
 121    }
 122    ...
 123    logger.log(Level.FINER, DiagnosisMessages.systemHealthStatus());
 124 </code></pre>
 125  * With the above code, the health status is collected unnecessarily even when
 126  * the log level FINER is disabled. With the Supplier-accepting version as
 127  * below, the status will only be collected when the log level FINER is
 128  * enabled.
 129  <pre><code>
 130 
 131    logger.log(Level.FINER, DiagnosisMessages::systemHealthStatus);
 132 </code></pre>
 133  * <p>
 134  * When mapping ResourceBundle names to ResourceBundles, the Logger
 135  * will first try to use the Thread's ContextClassLoader.  If that
 136  * is null it will try the
 137  * {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader} instead.
 138  * <p>
 139  * Formatting (including localization) is the responsibility of
 140  * the output Handler, which will typically call a Formatter.
 141  * <p>
 142  * Note that formatting need not occur synchronously.  It may be delayed
 143  * until a LogRecord is actually written to an external sink.
 144  * <p>
 145  * The logging methods are grouped in five main categories:
 146  * <ul>
 147  * <li><p>
 148  *     There are a set of "log" methods that take a log level, a message
 149  *     string, and optionally some parameters to the message string.
 150  * <li><p>
 151  *     There are a set of "logp" methods (for "log precise") that are
 152  *     like the "log" methods, but also take an explicit source class name
 153  *     and method name.
 154  * <li><p>
 155  *     There are a set of "logrb" method (for "log with resource bundle")
 156  *     that are like the "logp" method, but also take an explicit resource
 157  *     bundle name for use in localizing the log message.
 158  * <li><p>
 159  *     There are convenience methods for tracing method entries (the
 160  *     "entering" methods), method returns (the "exiting" methods) and
 161  *     throwing exceptions (the "throwing" methods).
 162  * <li><p>
 163  *     Finally, there are a set of convenience methods for use in the
 164  *     very simplest cases, when a developer simply wants to log a
 165  *     simple string at a given log level.  These methods are named
 166  *     after the standard Level names ("severe", "warning", "info", etc.)
 167  *     and take a single argument, a message string.
 168  * </ul>
 169  * <p>
 170  * For the methods that do not take an explicit source name and
 171  * method name, the Logging framework will make a "best effort"
 172  * to determine which class and method called into the logging method.
 173  * However, it is important to realize that this automatically inferred
 174  * information may only be approximate (or may even be quite wrong!).
 175  * Virtual machines are allowed to do extensive optimizations when
 176  * JITing and may entirely remove stack frames, making it impossible
 177  * to reliably locate the calling class and method.
 178  * <P>
 179  * All methods on Logger are multi-thread safe.
 180  * <p>
 181  * <b>Subclassing Information:</b> Note that a LogManager class may
 182  * provide its own implementation of named Loggers for any point in
 183  * the namespace.  Therefore, any subclasses of Logger (unless they
 184  * are implemented in conjunction with a new LogManager class) should
 185  * take care to obtain a Logger instance from the LogManager class and
 186  * should delegate operations such as "isLoggable" and "log(LogRecord)"
 187  * to that instance.  Note that in order to intercept all logging
 188  * output, subclasses need only override the log(LogRecord) method.
 189  * All the other logging methods are implemented as calls on this
 190  * log(LogRecord) method.
 191  *
 192  * @since 1.4
 193  */
 194 public class Logger {
 195     private static final Handler emptyHandlers[] = new Handler[0];
 196     private static final int offValue = Level.OFF.intValue();
 197     private LogManager manager;
 198     private String name;
 199     private final CopyOnWriteArrayList<Handler> handlers =
 200         new CopyOnWriteArrayList<>();
 201     private String resourceBundleName;
 202     private volatile boolean useParentHandlers = true;
 203     private volatile Filter filter;
 204     private boolean anonymous;
 205 
 206     private ResourceBundle catalog;     // Cached resource bundle
 207     private String catalogName;         // name associated with catalog
 208     private Locale catalogLocale;       // locale associated with catalog
 209 
 210     // The fields relating to parent-child relationships and levels
 211     // are managed under a separate lock, the treeLock.
 212     private static Object treeLock = new Object();
 213     // We keep weak references from parents to children, but strong
 214     // references from children to parents.
 215     private volatile Logger parent;    // our nearest parent.
 216     private ArrayList<LogManager.LoggerWeakRef> kids;   // WeakReferences to loggers that have us as parent
 217     private volatile Level levelObject;
 218     private volatile int levelValue;  // current effective level value
 219     private WeakReference<ClassLoader> callersClassLoaderRef;
 220 
 221     /**
 222      * GLOBAL_LOGGER_NAME is a name for the global logger.
 223      *
 224      * @since 1.6
 225      */
 226     public static final String GLOBAL_LOGGER_NAME = "global";
 227 
 228     /**
 229      * Return global logger object with the name Logger.GLOBAL_LOGGER_NAME.
 230      *
 231      * @return global logger object
 232      * @since 1.7
 233      */
 234     public static final Logger getGlobal() {
 235         // In order to break a cyclic dependence between the LogManager
 236         // and Logger static initializers causing deadlocks, the global
 237         // logger is created with a special constructor that does not
 238         // initialize its log manager.
 239         //
 240         // If an application calls Logger.getGlobal() before any logger
 241         // has been initialized, it is therefore possible that the
 242         // LogManager class has not been initialized yet, and therefore
 243         // Logger.global.manager will be null.
 244         //
 245         // In order to finish the initialization of the global logger, we
 246         // will therefore call LogManager.getLogManager() here.
 247         //
 248         // To prevent race conditions we also need to call
 249         // LogManager.getLogManager() unconditionally here.
 250         // Indeed we cannot rely on the observed value of global.manager,
 251         // because global.manager will become not null somewhere during
 252         // the initialization of LogManager.
 253         // If two threads are calling getGlobal() concurrently, one thread
 254         // will see global.manager null and call LogManager.getLogManager(),
 255         // but the other thread could come in at a time when global.manager
 256         // is already set although ensureLogManagerInitialized is not finished
 257         // yet...
 258         // Calling LogManager.getLogManager() unconditionally will fix that.
 259 
 260         LogManager.getLogManager();
 261 
 262         // Now the global LogManager should be initialized,
 263         // and the global logger should have been added to
 264         // it, unless we were called within the constructor of a LogManager
 265         // subclass installed as LogManager, in which case global.manager
 266         // would still be null, and global will be lazily initialized later on.
 267 
 268         return global;
 269     }
 270 
 271     /**
 272      * The "global" Logger object is provided as a convenience to developers
 273      * who are making casual use of the Logging package.  Developers
 274      * who are making serious use of the logging package (for example
 275      * in products) should create and use their own Logger objects,
 276      * with appropriate names, so that logging can be controlled on a
 277      * suitable per-Logger granularity. Developers also need to keep a
 278      * strong reference to their Logger objects to prevent them from
 279      * being garbage collected.
 280      * <p>
 281      * @deprecated Initialization of this field is prone to deadlocks.
 282      * The field must be initialized by the Logger class initialization
 283      * which may cause deadlocks with the LogManager class initialization.
 284      * In such cases two class initialization wait for each other to complete.
 285      * The preferred way to get the global logger object is via the call
 286      * <code>Logger.getGlobal()</code>.
 287      * For compatibility with old JDK versions where the
 288      * <code>Logger.getGlobal()</code> is not available use the call
 289      * <code>Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)</code>
 290      * or <code>Logger.getLogger("global")</code>.
 291      */
 292     @Deprecated
 293     public static final Logger global = new Logger(GLOBAL_LOGGER_NAME);
 294 
 295     /**
 296      * Protected method to construct a logger for a named subsystem.
 297      * <p>
 298      * The logger will be initially configured with a null Level
 299      * and with useParentHandlers set to true.
 300      *
 301      * @param   name    A name for the logger.  This should
 302      *                          be a dot-separated name and should normally
 303      *                          be based on the package name or class name
 304      *                          of the subsystem, such as java.net
 305      *                          or javax.swing.  It may be null for anonymous Loggers.
 306      * @param   resourceBundleName  name of ResourceBundle to be used for localizing
 307      *                          messages for this logger.  May be null if none
 308      *                          of the messages require localization.
 309      * @throws MissingResourceException if the resourceBundleName is non-null and
 310      *             no corresponding resource can be found.
 311      */
 312     protected Logger(String name, String resourceBundleName) {
 313         this(name, resourceBundleName, null, LogManager.getLogManager());
 314     }
 315 
 316     Logger(String name, String resourceBundleName, Class<?> caller, LogManager manager) {
 317         this.manager = manager;
 318         setupResourceInfo(resourceBundleName, caller);
 319         this.name = name;
 320         levelValue = Level.INFO.intValue();
 321     }
 322 
 323     private void setCallersClassLoaderRef(Class<?> caller) {
 324         ClassLoader callersClassLoader = ((caller != null)
 325                                          ? caller.getClassLoader()
 326                                          : null);
 327         if (callersClassLoader != null) {
 328             this.callersClassLoaderRef = new WeakReference(callersClassLoader);
 329         }
 330     }
 331 
 332     private ClassLoader getCallersClassLoader() {
 333         return (callersClassLoaderRef != null)
 334                 ? callersClassLoaderRef.get()
 335                 : null;
 336     }
 337 
 338     // This constructor is used only to create the global Logger.
 339     // It is needed to break a cyclic dependence between the LogManager
 340     // and Logger static initializers causing deadlocks.
 341     private Logger(String name) {
 342         // The manager field is not initialized here.
 343         this.name = name;
 344         levelValue = Level.INFO.intValue();
 345     }
 346 
 347     // It is called from LoggerContext.addLocalLogger() when the logger
 348     // is actually added to a LogManager.
 349     void setLogManager(LogManager manager) {
 350         this.manager = manager;
 351     }
 352 
 353     private void checkPermission() throws SecurityException {
 354         if (!anonymous) {
 355             if (manager == null) {
 356                 // Complete initialization of the global Logger.
 357                 manager = LogManager.getLogManager();
 358             }
 359             manager.checkPermission();
 360         }
 361     }
 362 
 363     // Until all JDK code converted to call sun.util.logging.PlatformLogger
 364     // (see 7054233), we need to determine if Logger.getLogger is to add
 365     // a system logger or user logger.
 366     //
 367     // As an interim solution, if the immediate caller whose caller loader is
 368     // null, we assume it's a system logger and add it to the system context.
 369     // These system loggers only set the resource bundle to the given
 370     // resource bundle name (rather than the default system resource bundle).
 371     private static class SystemLoggerHelper {
 372         static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck");
 373         private static boolean getBooleanProperty(final String key) {
 374             String s = AccessController.doPrivileged(new PrivilegedAction<String>() {
 375                 public String run() {
 376                     return System.getProperty(key);
 377                 }
 378             });
 379             return Boolean.valueOf(s);
 380         }
 381     }
 382 
 383     private static Logger demandLogger(String name, String resourceBundleName, Class<?> caller) {
 384         LogManager manager = LogManager.getLogManager();
 385         SecurityManager sm = System.getSecurityManager();
 386         if (sm != null && !SystemLoggerHelper.disableCallerCheck) {
 387             if (caller.getClassLoader() == null) {
 388                 return manager.demandSystemLogger(name, resourceBundleName);
 389             }
 390         }
 391         return manager.demandLogger(name, resourceBundleName, caller);
 392         // ends up calling new Logger(name, resourceBundleName, caller)
 393         // iff the logger doesn't exist already
 394     }
 395 
 396     /**
 397      * Find or create a logger for a named subsystem.  If a logger has
 398      * already been created with the given name it is returned.  Otherwise
 399      * a new logger is created.
 400      * <p>
 401      * If a new logger is created its log level will be configured
 402      * based on the LogManager configuration and it will configured
 403      * to also send logging output to its parent's Handlers.  It will
 404      * be registered in the LogManager global namespace.
 405      * <p>
 406      * Note: The LogManager may only retain a weak reference to the newly
 407      * created Logger. It is important to understand that a previously
 408      * created Logger with the given name may be garbage collected at any
 409      * time if there is no strong reference to the Logger. In particular,
 410      * this means that two back-to-back calls like
 411      * {@code getLogger("MyLogger").log(...)} may use different Logger
 412      * objects named "MyLogger" if there is no strong reference to the
 413      * Logger named "MyLogger" elsewhere in the program.
 414      *
 415      * @param   name            A name for the logger.  This should
 416      *                          be a dot-separated name and should normally
 417      *                          be based on the package name or class name
 418      *                          of the subsystem, such as java.net
 419      *                          or javax.swing
 420      * @return a suitable Logger
 421      * @throws NullPointerException if the name is null.
 422      */
 423 
 424     // Synchronization is not required here. All synchronization for
 425     // adding a new Logger object is handled by LogManager.addLogger().
 426     @CallerSensitive
 427     public static Logger getLogger(String name) {
 428         // This method is intentionally not a wrapper around a call
 429         // to getLogger(name, resourceBundleName). If it were then
 430         // this sequence:
 431         //
 432         //     getLogger("Foo", "resourceBundleForFoo");
 433         //     getLogger("Foo");
 434         //
 435         // would throw an IllegalArgumentException in the second call
 436         // because the wrapper would result in an attempt to replace
 437         // the existing "resourceBundleForFoo" with null.
 438         return demandLogger(name, null, Reflection.getCallerClass());
 439     }
 440 
 441     /**
 442      * Find or create a logger for a named subsystem.  If a logger has
 443      * already been created with the given name it is returned.  Otherwise
 444      * a new logger is created.
 445      * <p>
 446      * If a new logger is created its log level will be configured
 447      * based on the LogManager and it will configured to also send logging
 448      * output to its parent's Handlers.  It will be registered in
 449      * the LogManager global namespace.
 450      * <p>
 451      * Note: The LogManager may only retain a weak reference to the newly
 452      * created Logger. It is important to understand that a previously
 453      * created Logger with the given name may be garbage collected at any
 454      * time if there is no strong reference to the Logger. In particular,
 455      * this means that two back-to-back calls like
 456      * {@code getLogger("MyLogger", ...).log(...)} may use different Logger
 457      * objects named "MyLogger" if there is no strong reference to the
 458      * Logger named "MyLogger" elsewhere in the program.
 459      * <p>
 460      * If the named Logger already exists and does not yet have a
 461      * localization resource bundle then the given resource bundle
 462      * name is used.  If the named Logger already exists and has
 463      * a different resource bundle name then an IllegalArgumentException
 464      * is thrown.
 465      * <p>
 466      * @param   name    A name for the logger.  This should
 467      *                          be a dot-separated name and should normally
 468      *                          be based on the package name or class name
 469      *                          of the subsystem, such as java.net
 470      *                          or javax.swing
 471      * @param   resourceBundleName  name of ResourceBundle to be used for localizing
 472      *                          messages for this logger. May be {@code null}
 473      *                          if none of the messages require localization.
 474      * @return a suitable Logger
 475      * @throws MissingResourceException if the resourceBundleName is non-null and
 476      *             no corresponding resource can be found.
 477      * @throws IllegalArgumentException if the Logger already exists and uses
 478      *             a different resource bundle name; or if
 479      *             {@code resourceBundleName} is {@code null} but the named
 480      *             logger has a resource bundle set.
 481      * @throws NullPointerException if the name is null.
 482      */
 483 
 484     // Synchronization is not required here. All synchronization for
 485     // adding a new Logger object is handled by LogManager.addLogger().
 486     @CallerSensitive
 487     public static Logger getLogger(String name, String resourceBundleName) {
 488         Class<?> callerClass = Reflection.getCallerClass();
 489         Logger result = demandLogger(name, resourceBundleName, callerClass);
 490 
 491         // MissingResourceException or IllegalArgumentException can be
 492         // thrown by setupResourceInfo().
 493         // We have to set the callers ClassLoader here in case demandLogger
 494         // above found a previously created Logger.  This can happen, for
 495         // example, if Logger.getLogger(name) is called and subsequently
 496         // Logger.getLogger(name, resourceBundleName) is called.  In this case
 497         // we won't necessarily have the correct classloader saved away, so
 498         // we need to set it here, too.
 499 
 500         result.setupResourceInfo(resourceBundleName, callerClass);
 501         return result;
 502     }
 503 
 504     // package-private
 505     // Add a platform logger to the system context.
 506     // i.e. caller of sun.util.logging.PlatformLogger.getLogger
 507     static Logger getPlatformLogger(String name) {
 508         LogManager manager = LogManager.getLogManager();
 509 
 510         // all loggers in the system context will default to
 511         // the system logger's resource bundle
 512         Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME);
 513         return result;
 514     }
 515 
 516     /**
 517      * Create an anonymous Logger.  The newly created Logger is not
 518      * registered in the LogManager namespace.  There will be no
 519      * access checks on updates to the logger.
 520      * <p>
 521      * This factory method is primarily intended for use from applets.
 522      * Because the resulting Logger is anonymous it can be kept private
 523      * by the creating class.  This removes the need for normal security
 524      * checks, which in turn allows untrusted applet code to update
 525      * the control state of the Logger.  For example an applet can do
 526      * a setLevel or an addHandler on an anonymous Logger.
 527      * <p>
 528      * Even although the new logger is anonymous, it is configured
 529      * to have the root logger ("") as its parent.  This means that
 530      * by default it inherits its effective level and handlers
 531      * from the root logger.
 532      * <p>
 533      *
 534      * @return a newly created private Logger
 535      */
 536     public static Logger getAnonymousLogger() {
 537         return getAnonymousLogger(null);
 538     }
 539 
 540     /**
 541      * Create an anonymous Logger.  The newly created Logger is not
 542      * registered in the LogManager namespace.  There will be no
 543      * access checks on updates to the logger.
 544      * <p>
 545      * This factory method is primarily intended for use from applets.
 546      * Because the resulting Logger is anonymous it can be kept private
 547      * by the creating class.  This removes the need for normal security
 548      * checks, which in turn allows untrusted applet code to update
 549      * the control state of the Logger.  For example an applet can do
 550      * a setLevel or an addHandler on an anonymous Logger.
 551      * <p>
 552      * Even although the new logger is anonymous, it is configured
 553      * to have the root logger ("") as its parent.  This means that
 554      * by default it inherits its effective level and handlers
 555      * from the root logger.
 556      * <p>
 557      * @param   resourceBundleName  name of ResourceBundle to be used for localizing
 558      *                          messages for this logger.
 559      *          May be null if none of the messages require localization.
 560      * @return a newly created private Logger
 561      * @throws MissingResourceException if the resourceBundleName is non-null and
 562      *             no corresponding resource can be found.
 563      */
 564 
 565     // Synchronization is not required here. All synchronization for
 566     // adding a new anonymous Logger object is handled by doSetParent().
 567     @CallerSensitive
 568     public static Logger getAnonymousLogger(String resourceBundleName) {
 569         LogManager manager = LogManager.getLogManager();
 570         // cleanup some Loggers that have been GC'ed
 571         manager.drainLoggerRefQueueBounded();
 572         Logger result = new Logger(null, resourceBundleName,
 573                                    Reflection.getCallerClass(), manager);
 574         result.anonymous = true;
 575         Logger root = manager.getLogger("");
 576         result.doSetParent(root);
 577         return result;
 578     }
 579 
 580     /**
 581      * Retrieve the localization resource bundle for this
 582      * logger for the current default locale.  Note that if
 583      * the result is null, then the Logger will use a resource
 584      * bundle inherited from its parent.
 585      *
 586      * @return localization bundle (may be null)
 587      */
 588     public ResourceBundle getResourceBundle() {
 589         return findResourceBundle(getResourceBundleName(), true);
 590     }
 591 
 592     /**
 593      * Retrieve the localization resource bundle name for this
 594      * logger.  Note that if the result is null, then the Logger
 595      * will use a resource bundle name inherited from its parent.
 596      *
 597      * @return localization bundle name (may be null)
 598      */
 599     public String getResourceBundleName() {
 600         return resourceBundleName;
 601     }
 602 
 603     /**
 604      * Set a filter to control output on this Logger.
 605      * <P>
 606      * After passing the initial "level" check, the Logger will
 607      * call this Filter to check if a log record should really
 608      * be published.
 609      *
 610      * @param   newFilter  a filter object (may be null)
 611      * @exception  SecurityException  if a security manager exists and if
 612      *             the caller does not have LoggingPermission("control").
 613      */
 614     public void setFilter(Filter newFilter) throws SecurityException {
 615         checkPermission();
 616         filter = newFilter;
 617     }
 618 
 619     /**
 620      * Get the current filter for this Logger.
 621      *
 622      * @return  a filter object (may be null)
 623      */
 624     public Filter getFilter() {
 625         return filter;
 626     }
 627 
 628     /**
 629      * Log a LogRecord.
 630      * <p>
 631      * All the other logging methods in this class call through
 632      * this method to actually perform any logging.  Subclasses can
 633      * override this single method to capture all log activity.
 634      *
 635      * @param record the LogRecord to be published
 636      */
 637     public void log(LogRecord record) {
 638         if (record.getLevel().intValue() < levelValue || levelValue == offValue) {
 639             return;
 640         }
 641         Filter theFilter = filter;
 642         if (theFilter != null && !theFilter.isLoggable(record)) {
 643             return;
 644         }
 645 
 646         // Post the LogRecord to all our Handlers, and then to
 647         // our parents' handlers, all the way up the tree.
 648 
 649         Logger logger = this;
 650         while (logger != null) {
 651             for (Handler handler : logger.getHandlers()) {
 652                 handler.publish(record);
 653             }
 654 
 655             if (!logger.getUseParentHandlers()) {
 656                 break;
 657             }
 658 
 659             logger = logger.getParent();
 660         }
 661     }
 662 
 663     // private support method for logging.
 664     // We fill in the logger name, resource bundle name, and
 665     // resource bundle and then call "void log(LogRecord)".
 666     private void doLog(LogRecord lr) {
 667         lr.setLoggerName(name);
 668         String ebname = getEffectiveResourceBundleName();
 669         if (ebname != null && !ebname.equals(SYSTEM_LOGGER_RB_NAME)) {
 670             lr.setResourceBundleName(ebname);
 671             lr.setResourceBundle(findResourceBundle(ebname, true));
 672         }
 673         log(lr);
 674     }
 675 
 676 
 677     //================================================================
 678     // Start of convenience methods WITHOUT className and methodName
 679     //================================================================
 680 
 681     /**
 682      * Log a message, with no arguments.
 683      * <p>
 684      * If the logger is currently enabled for the given message
 685      * level then the given message is forwarded to all the
 686      * registered output Handler objects.
 687      * <p>
 688      * @param   level   One of the message level identifiers, e.g., SEVERE
 689      * @param   msg     The string message (or a key in the message catalog)
 690      */
 691     public void log(Level level, String msg) {
 692         if (level.intValue() < levelValue || levelValue == offValue) {
 693             return;
 694         }
 695         LogRecord lr = new LogRecord(level, msg);
 696         doLog(lr);
 697     }
 698 
 699     /**
 700      * Log a message, which is only to be constructed if the logging level
 701      * is such that the message will actually be logged.
 702      * <p>
 703      * If the logger is currently enabled for the given message
 704      * level then the message is constructed by invoking the provided
 705      * supplier function and forwarded to all the registered output
 706      * Handler objects.
 707      * <p>
 708      * @param   level   One of the message level identifiers, e.g., SEVERE
 709      * @param   msgSupplier   A function, which when called, produces the
 710      *                        desired log message
 711      */
 712     public void log(Level level, Supplier<String> msgSupplier) {
 713         if (level.intValue() < levelValue || levelValue == offValue) {
 714             return;
 715         }
 716         LogRecord lr = new LogRecord(level, msgSupplier.get());
 717         doLog(lr);
 718     }
 719 
 720     /**
 721      * Log a message, with one object parameter.
 722      * <p>
 723      * If the logger is currently enabled for the given message
 724      * level then a corresponding LogRecord is created and forwarded
 725      * to all the registered output Handler objects.
 726      * <p>
 727      * @param   level   One of the message level identifiers, e.g., SEVERE
 728      * @param   msg     The string message (or a key in the message catalog)
 729      * @param   param1  parameter to the message
 730      */
 731     public void log(Level level, String msg, Object param1) {
 732         if (level.intValue() < levelValue || levelValue == offValue) {
 733             return;
 734         }
 735         LogRecord lr = new LogRecord(level, msg);
 736         Object params[] = { param1 };
 737         lr.setParameters(params);
 738         doLog(lr);
 739     }
 740 
 741     /**
 742      * Log a message, with an array of object arguments.
 743      * <p>
 744      * If the logger is currently enabled for the given message
 745      * level then a corresponding LogRecord is created and forwarded
 746      * to all the registered output Handler objects.
 747      * <p>
 748      * @param   level   One of the message level identifiers, e.g., SEVERE
 749      * @param   msg     The string message (or a key in the message catalog)
 750      * @param   params  array of parameters to the message
 751      */
 752     public void log(Level level, String msg, Object params[]) {
 753         if (level.intValue() < levelValue || levelValue == offValue) {
 754             return;
 755         }
 756         LogRecord lr = new LogRecord(level, msg);
 757         lr.setParameters(params);
 758         doLog(lr);
 759     }
 760 
 761     /**
 762      * Log a message, with associated Throwable information.
 763      * <p>
 764      * If the logger is currently enabled for the given message
 765      * level then the given arguments are stored in a LogRecord
 766      * which is forwarded to all registered output handlers.
 767      * <p>
 768      * Note that the thrown argument is stored in the LogRecord thrown
 769      * property, rather than the LogRecord parameters property.  Thus it is
 770      * processed specially by output Formatters and is not treated
 771      * as a formatting parameter to the LogRecord message property.
 772      * <p>
 773      * @param   level   One of the message level identifiers, e.g., SEVERE
 774      * @param   msg     The string message (or a key in the message catalog)
 775      * @param   thrown  Throwable associated with log message.
 776      */
 777     public void log(Level level, String msg, Throwable thrown) {
 778         if (level.intValue() < levelValue || levelValue == offValue) {
 779             return;
 780         }
 781         LogRecord lr = new LogRecord(level, msg);
 782         lr.setThrown(thrown);
 783         doLog(lr);
 784     }
 785 
 786     /**
 787      * Log a lazily constructed message, with associated Throwable information.
 788      * <p>
 789      * If the logger is currently enabled for the given message level then the
 790      * message is constructed by invoking the provided supplier function. The
 791      * message and the given {@link Throwable} are then stored in a {@link
 792      * LogRecord} which is forwarded to all registered output handlers.
 793      * <p>
 794      * Note that the thrown argument is stored in the LogRecord thrown
 795      * property, rather than the LogRecord parameters property.  Thus it is
 796      * processed specially by output Formatters and is not treated
 797      * as a formatting parameter to the LogRecord message property.
 798      * <p>
 799      * @param   level   One of the message level identifiers, e.g., SEVERE
 800      * @param   thrown  Throwable associated with log message.
 801      * @param   msgSupplier   A function, which when called, produces the
 802      *                        desired log message
 803      * @since   1.8
 804      */
 805     public void log(Level level, Throwable thrown, Supplier<String> msgSupplier) {
 806         if (level.intValue() < levelValue || levelValue == offValue) {
 807             return;
 808         }
 809         LogRecord lr = new LogRecord(level, msgSupplier.get());
 810         lr.setThrown(thrown);
 811         doLog(lr);
 812     }
 813 
 814     //================================================================
 815     // Start of convenience methods WITH className and methodName
 816     //================================================================
 817 
 818     /**
 819      * Log a message, specifying source class and method,
 820      * with no arguments.
 821      * <p>
 822      * If the logger is currently enabled for the given message
 823      * level then the given message is forwarded to all the
 824      * registered output Handler objects.
 825      * <p>
 826      * @param   level   One of the message level identifiers, e.g., SEVERE
 827      * @param   sourceClass    name of class that issued the logging request
 828      * @param   sourceMethod   name of method that issued the logging request
 829      * @param   msg     The string message (or a key in the message catalog)
 830      */
 831     public void logp(Level level, String sourceClass, String sourceMethod, String msg) {
 832         if (level.intValue() < levelValue || levelValue == offValue) {
 833             return;
 834         }
 835         LogRecord lr = new LogRecord(level, msg);
 836         lr.setSourceClassName(sourceClass);
 837         lr.setSourceMethodName(sourceMethod);
 838         doLog(lr);
 839     }
 840 
 841     /**
 842      * Log a lazily constructed message, specifying source class and method,
 843      * with no arguments.
 844      * <p>
 845      * If the logger is currently enabled for the given message
 846      * level then the message is constructed by invoking the provided
 847      * supplier function and forwarded to all the registered output
 848      * Handler objects.
 849      * <p>
 850      * @param   level   One of the message level identifiers, e.g., SEVERE
 851      * @param   sourceClass    name of class that issued the logging request
 852      * @param   sourceMethod   name of method that issued the logging request
 853      * @param   msgSupplier   A function, which when called, produces the
 854      *                        desired log message
 855      * @since   1.8
 856      */
 857     public void logp(Level level, String sourceClass, String sourceMethod,
 858                      Supplier<String> msgSupplier) {
 859         if (level.intValue() < levelValue || levelValue == offValue) {
 860             return;
 861         }
 862         LogRecord lr = new LogRecord(level, msgSupplier.get());
 863         lr.setSourceClassName(sourceClass);
 864         lr.setSourceMethodName(sourceMethod);
 865         doLog(lr);
 866     }
 867 
 868     /**
 869      * Log a message, specifying source class and method,
 870      * with a single object parameter to the log message.
 871      * <p>
 872      * If the logger is currently enabled for the given message
 873      * level then a corresponding LogRecord is created and forwarded
 874      * to all the registered output Handler objects.
 875      * <p>
 876      * @param   level   One of the message level identifiers, e.g., SEVERE
 877      * @param   sourceClass    name of class that issued the logging request
 878      * @param   sourceMethod   name of method that issued the logging request
 879      * @param   msg      The string message (or a key in the message catalog)
 880      * @param   param1    Parameter to the log message.
 881      */
 882     public void logp(Level level, String sourceClass, String sourceMethod,
 883                                                 String msg, Object param1) {
 884         if (level.intValue() < levelValue || levelValue == offValue) {
 885             return;
 886         }
 887         LogRecord lr = new LogRecord(level, msg);
 888         lr.setSourceClassName(sourceClass);
 889         lr.setSourceMethodName(sourceMethod);
 890         Object params[] = { param1 };
 891         lr.setParameters(params);
 892         doLog(lr);
 893     }
 894 
 895     /**
 896      * Log a message, specifying source class and method,
 897      * with an array of object arguments.
 898      * <p>
 899      * If the logger is currently enabled for the given message
 900      * level then a corresponding LogRecord is created and forwarded
 901      * to all the registered output Handler objects.
 902      * <p>
 903      * @param   level   One of the message level identifiers, e.g., SEVERE
 904      * @param   sourceClass    name of class that issued the logging request
 905      * @param   sourceMethod   name of method that issued the logging request
 906      * @param   msg     The string message (or a key in the message catalog)
 907      * @param   params  Array of parameters to the message
 908      */
 909     public void logp(Level level, String sourceClass, String sourceMethod,
 910                                                 String msg, Object params[]) {
 911         if (level.intValue() < levelValue || levelValue == offValue) {
 912             return;
 913         }
 914         LogRecord lr = new LogRecord(level, msg);
 915         lr.setSourceClassName(sourceClass);
 916         lr.setSourceMethodName(sourceMethod);
 917         lr.setParameters(params);
 918         doLog(lr);
 919     }
 920 
 921     /**
 922      * Log a message, specifying source class and method,
 923      * with associated Throwable information.
 924      * <p>
 925      * If the logger is currently enabled for the given message
 926      * level then the given arguments are stored in a LogRecord
 927      * which is forwarded to all registered output handlers.
 928      * <p>
 929      * Note that the thrown argument is stored in the LogRecord thrown
 930      * property, rather than the LogRecord parameters property.  Thus it is
 931      * processed specially by output Formatters and is not treated
 932      * as a formatting parameter to the LogRecord message property.
 933      * <p>
 934      * @param   level   One of the message level identifiers, e.g., SEVERE
 935      * @param   sourceClass    name of class that issued the logging request
 936      * @param   sourceMethod   name of method that issued the logging request
 937      * @param   msg     The string message (or a key in the message catalog)
 938      * @param   thrown  Throwable associated with log message.
 939      */
 940     public void logp(Level level, String sourceClass, String sourceMethod,
 941                      String msg, Throwable thrown) {
 942         if (level.intValue() < levelValue || levelValue == offValue) {
 943             return;
 944         }
 945         LogRecord lr = new LogRecord(level, msg);
 946         lr.setSourceClassName(sourceClass);
 947         lr.setSourceMethodName(sourceMethod);
 948         lr.setThrown(thrown);
 949         doLog(lr);
 950     }
 951 
 952     /**
 953      * Log a lazily constructed message, specifying source class and method,
 954      * with associated Throwable information.
 955      * <p>
 956      * If the logger is currently enabled for the given message level then the
 957      * message is constructed by invoking the provided supplier function. The
 958      * message and the given {@link Throwable} are then stored in a {@link
 959      * LogRecord} which is forwarded to all registered output handlers.
 960      * <p>
 961      * Note that the thrown argument is stored in the LogRecord thrown
 962      * property, rather than the LogRecord parameters property.  Thus it is
 963      * processed specially by output Formatters and is not treated
 964      * as a formatting parameter to the LogRecord message property.
 965      * <p>
 966      * @param   level   One of the message level identifiers, e.g., SEVERE
 967      * @param   sourceClass    name of class that issued the logging request
 968      * @param   sourceMethod   name of method that issued the logging request
 969      * @param   thrown  Throwable associated with log message.
 970      * @param   msgSupplier   A function, which when called, produces the
 971      *                        desired log message
 972      * @since   1.8
 973      */
 974     public void logp(Level level, String sourceClass, String sourceMethod,
 975                      Throwable thrown, Supplier<String> msgSupplier) {
 976         if (level.intValue() < levelValue || levelValue == offValue) {
 977             return;
 978         }
 979         LogRecord lr = new LogRecord(level, msgSupplier.get());
 980         lr.setSourceClassName(sourceClass);
 981         lr.setSourceMethodName(sourceMethod);
 982         lr.setThrown(thrown);
 983         doLog(lr);
 984     }
 985 
 986 
 987     //=========================================================================
 988     // Start of convenience methods WITH className, methodName and bundle name.
 989     //=========================================================================
 990 
 991     // Private support method for logging for "logrb" methods.
 992     // We fill in the logger name, resource bundle name, and
 993     // resource bundle and then call "void log(LogRecord)".
 994     private void doLog(LogRecord lr, String rbname) {
 995         lr.setLoggerName(name);
 996         if (rbname != null) {
 997             lr.setResourceBundleName(rbname);
 998             lr.setResourceBundle(findResourceBundle(rbname, false));
 999         }
1000         log(lr);
1001     }
1002 
1003     /**
1004      * Log a message, specifying source class, method, and resource bundle name
1005      * with no arguments.
1006      * <p>
1007      * If the logger is currently enabled for the given message
1008      * level then the given message is forwarded to all the
1009      * registered output Handler objects.
1010      * <p>
1011      * The msg string is localized using the named resource bundle.  If the
1012      * resource bundle name is null, or an empty String or invalid
1013      * then the msg string is not localized.
1014      * <p>
1015      * @param   level   One of the message level identifiers, e.g., SEVERE
1016      * @param   sourceClass    name of class that issued the logging request
1017      * @param   sourceMethod   name of method that issued the logging request
1018      * @param   bundleName     name of resource bundle to localize msg,
1019      *                         can be null
1020      * @param   msg     The string message (or a key in the message catalog)
1021      */
1022     public void logrb(Level level, String sourceClass, String sourceMethod,
1023                                 String bundleName, String msg) {
1024         if (level.intValue() < levelValue || levelValue == offValue) {
1025             return;
1026         }
1027         LogRecord lr = new LogRecord(level, msg);
1028         lr.setSourceClassName(sourceClass);
1029         lr.setSourceMethodName(sourceMethod);
1030         doLog(lr, bundleName);
1031     }
1032 
1033     /**
1034      * Log a message, specifying source class, method, and resource bundle name,
1035      * with a single object parameter to the log message.
1036      * <p>
1037      * If the logger is currently enabled for the given message
1038      * level then a corresponding LogRecord is created and forwarded
1039      * to all the registered output Handler objects.
1040      * <p>
1041      * The msg string is localized using the named resource bundle.  If the
1042      * resource bundle name is null, or an empty String or invalid
1043      * then the msg string is not localized.
1044      * <p>
1045      * @param   level   One of the message level identifiers, e.g., SEVERE
1046      * @param   sourceClass    name of class that issued the logging request
1047      * @param   sourceMethod   name of method that issued the logging request
1048      * @param   bundleName     name of resource bundle to localize msg,
1049      *                         can be null
1050      * @param   msg      The string message (or a key in the message catalog)
1051      * @param   param1    Parameter to the log message.
1052      */
1053     public void logrb(Level level, String sourceClass, String sourceMethod,
1054                                 String bundleName, String msg, Object param1) {
1055         if (level.intValue() < levelValue || levelValue == offValue) {
1056             return;
1057         }
1058         LogRecord lr = new LogRecord(level, msg);
1059         lr.setSourceClassName(sourceClass);
1060         lr.setSourceMethodName(sourceMethod);
1061         Object params[] = { param1 };
1062         lr.setParameters(params);
1063         doLog(lr, bundleName);
1064     }
1065 
1066     /**
1067      * Log a message, specifying source class, method, and resource bundle name,
1068      * with an array of object arguments.
1069      * <p>
1070      * If the logger is currently enabled for the given message
1071      * level then a corresponding LogRecord is created and forwarded
1072      * to all the registered output Handler objects.
1073      * <p>
1074      * The msg string is localized using the named resource bundle.  If the
1075      * resource bundle name is null, or an empty String or invalid
1076      * then the msg string is not localized.
1077      * <p>
1078      * @param   level   One of the message level identifiers, e.g., SEVERE
1079      * @param   sourceClass    name of class that issued the logging request
1080      * @param   sourceMethod   name of method that issued the logging request
1081      * @param   bundleName     name of resource bundle to localize msg,
1082      *                         can be null.
1083      * @param   msg     The string message (or a key in the message catalog)
1084      * @param   params  Array of parameters to the message
1085      */
1086     public void logrb(Level level, String sourceClass, String sourceMethod,
1087                                 String bundleName, String msg, Object params[]) {
1088         if (level.intValue() < levelValue || levelValue == offValue) {
1089             return;
1090         }
1091         LogRecord lr = new LogRecord(level, msg);
1092         lr.setSourceClassName(sourceClass);
1093         lr.setSourceMethodName(sourceMethod);
1094         lr.setParameters(params);
1095         doLog(lr, bundleName);
1096     }
1097 
1098     /**
1099      * Log a message, specifying source class, method, and resource bundle name,
1100      * with associated Throwable information.
1101      * <p>
1102      * If the logger is currently enabled for the given message
1103      * level then the given arguments are stored in a LogRecord
1104      * which is forwarded to all registered output handlers.
1105      * <p>
1106      * The msg string is localized using the named resource bundle.  If the
1107      * resource bundle name is null, or an empty String or invalid
1108      * then the msg string is not localized.
1109      * <p>
1110      * Note that the thrown argument is stored in the LogRecord thrown
1111      * property, rather than the LogRecord parameters property.  Thus it is
1112      * processed specially by output Formatters and is not treated
1113      * as a formatting parameter to the LogRecord message property.
1114      * <p>
1115      * @param   level   One of the message level identifiers, e.g., SEVERE
1116      * @param   sourceClass    name of class that issued the logging request
1117      * @param   sourceMethod   name of method that issued the logging request
1118      * @param   bundleName     name of resource bundle to localize msg,
1119      *                         can be null
1120      * @param   msg     The string message (or a key in the message catalog)
1121      * @param   thrown  Throwable associated with log message.
1122      */
1123     public void logrb(Level level, String sourceClass, String sourceMethod,
1124                                         String bundleName, String msg, Throwable thrown) {
1125         if (level.intValue() < levelValue || levelValue == offValue) {
1126             return;
1127         }
1128         LogRecord lr = new LogRecord(level, msg);
1129         lr.setSourceClassName(sourceClass);
1130         lr.setSourceMethodName(sourceMethod);
1131         lr.setThrown(thrown);
1132         doLog(lr, bundleName);
1133     }
1134 
1135 
1136     //======================================================================
1137     // Start of convenience methods for logging method entries and returns.
1138     //======================================================================
1139 
1140     /**
1141      * Log a method entry.
1142      * <p>
1143      * This is a convenience method that can be used to log entry
1144      * to a method.  A LogRecord with message "ENTRY", log level
1145      * FINER, and the given sourceMethod and sourceClass is logged.
1146      * <p>
1147      * @param   sourceClass    name of class that issued the logging request
1148      * @param   sourceMethod   name of method that is being entered
1149      */
1150     public void entering(String sourceClass, String sourceMethod) {
1151         if (Level.FINER.intValue() < levelValue) {
1152             return;
1153         }
1154         logp(Level.FINER, sourceClass, sourceMethod, "ENTRY");
1155     }
1156 
1157     /**
1158      * Log a method entry, with one parameter.
1159      * <p>
1160      * This is a convenience method that can be used to log entry
1161      * to a method.  A LogRecord with message "ENTRY {0}", log level
1162      * FINER, and the given sourceMethod, sourceClass, and parameter
1163      * is logged.
1164      * <p>
1165      * @param   sourceClass    name of class that issued the logging request
1166      * @param   sourceMethod   name of method that is being entered
1167      * @param   param1         parameter to the method being entered
1168      */
1169     public void entering(String sourceClass, String sourceMethod, Object param1) {
1170         if (Level.FINER.intValue() < levelValue) {
1171             return;
1172         }
1173         Object params[] = { param1 };
1174         logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params);
1175     }
1176 
1177     /**
1178      * Log a method entry, with an array of parameters.
1179      * <p>
1180      * This is a convenience method that can be used to log entry
1181      * to a method.  A LogRecord with message "ENTRY" (followed by a
1182      * format {N} indicator for each entry in the parameter array),
1183      * log level FINER, and the given sourceMethod, sourceClass, and
1184      * parameters is logged.
1185      * <p>
1186      * @param   sourceClass    name of class that issued the logging request
1187      * @param   sourceMethod   name of method that is being entered
1188      * @param   params         array of parameters to the method being entered
1189      */
1190     public void entering(String sourceClass, String sourceMethod, Object params[]) {
1191         if (Level.FINER.intValue() < levelValue) {
1192             return;
1193         }
1194         String msg = "ENTRY";
1195         if (params == null ) {
1196            logp(Level.FINER, sourceClass, sourceMethod, msg);
1197            return;
1198         }
1199         for (int i = 0; i < params.length; i++) {
1200             msg = msg + " {" + i + "}";
1201         }
1202         logp(Level.FINER, sourceClass, sourceMethod, msg, params);
1203     }
1204 
1205     /**
1206      * Log a method return.
1207      * <p>
1208      * This is a convenience method that can be used to log returning
1209      * from a method.  A LogRecord with message "RETURN", log level
1210      * FINER, and the given sourceMethod and sourceClass is logged.
1211      * <p>
1212      * @param   sourceClass    name of class that issued the logging request
1213      * @param   sourceMethod   name of the method
1214      */
1215     public void exiting(String sourceClass, String sourceMethod) {
1216         if (Level.FINER.intValue() < levelValue) {
1217             return;
1218         }
1219         logp(Level.FINER, sourceClass, sourceMethod, "RETURN");
1220     }
1221 
1222 
1223     /**
1224      * Log a method return, with result object.
1225      * <p>
1226      * This is a convenience method that can be used to log returning
1227      * from a method.  A LogRecord with message "RETURN {0}", log level
1228      * FINER, and the gives sourceMethod, sourceClass, and result
1229      * object is logged.
1230      * <p>
1231      * @param   sourceClass    name of class that issued the logging request
1232      * @param   sourceMethod   name of the method
1233      * @param   result  Object that is being returned
1234      */
1235     public void exiting(String sourceClass, String sourceMethod, Object result) {
1236         if (Level.FINER.intValue() < levelValue) {
1237             return;
1238         }
1239         Object params[] = { result };
1240         logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result);
1241     }
1242 
1243     /**
1244      * Log throwing an exception.
1245      * <p>
1246      * This is a convenience method to log that a method is
1247      * terminating by throwing an exception.  The logging is done
1248      * using the FINER level.
1249      * <p>
1250      * If the logger is currently enabled for the given message
1251      * level then the given arguments are stored in a LogRecord
1252      * which is forwarded to all registered output handlers.  The
1253      * LogRecord's message is set to "THROW".
1254      * <p>
1255      * Note that the thrown argument is stored in the LogRecord thrown
1256      * property, rather than the LogRecord parameters property.  Thus it is
1257      * processed specially by output Formatters and is not treated
1258      * as a formatting parameter to the LogRecord message property.
1259      * <p>
1260      * @param   sourceClass    name of class that issued the logging request
1261      * @param   sourceMethod  name of the method.
1262      * @param   thrown  The Throwable that is being thrown.
1263      */
1264     public void throwing(String sourceClass, String sourceMethod, Throwable thrown) {
1265         if (Level.FINER.intValue() < levelValue || levelValue == offValue ) {
1266             return;
1267         }
1268         LogRecord lr = new LogRecord(Level.FINER, "THROW");
1269         lr.setSourceClassName(sourceClass);
1270         lr.setSourceMethodName(sourceMethod);
1271         lr.setThrown(thrown);
1272         doLog(lr);
1273     }
1274 
1275     //=======================================================================
1276     // Start of simple convenience methods using level names as method names
1277     //=======================================================================
1278 
1279     /**
1280      * Log a SEVERE message.
1281      * <p>
1282      * If the logger is currently enabled for the SEVERE message
1283      * level then the given message is forwarded to all the
1284      * registered output Handler objects.
1285      * <p>
1286      * @param   msg     The string message (or a key in the message catalog)
1287      */
1288     public void severe(String msg) {
1289         if (Level.SEVERE.intValue() < levelValue) {
1290             return;
1291         }
1292         log(Level.SEVERE, msg);
1293     }
1294 
1295     /**
1296      * Log a WARNING message.
1297      * <p>
1298      * If the logger is currently enabled for the WARNING message
1299      * level then the given message is forwarded to all the
1300      * registered output Handler objects.
1301      * <p>
1302      * @param   msg     The string message (or a key in the message catalog)
1303      */
1304     public void warning(String msg) {
1305         if (Level.WARNING.intValue() < levelValue) {
1306             return;
1307         }
1308         log(Level.WARNING, msg);
1309     }
1310 
1311     /**
1312      * Log an INFO message.
1313      * <p>
1314      * If the logger is currently enabled for the INFO message
1315      * level then the given message is forwarded to all the
1316      * registered output Handler objects.
1317      * <p>
1318      * @param   msg     The string message (or a key in the message catalog)
1319      */
1320     public void info(String msg) {
1321         if (Level.INFO.intValue() < levelValue) {
1322             return;
1323         }
1324         log(Level.INFO, msg);
1325     }
1326 
1327     /**
1328      * Log a CONFIG message.
1329      * <p>
1330      * If the logger is currently enabled for the CONFIG message
1331      * level then the given message is forwarded to all the
1332      * registered output Handler objects.
1333      * <p>
1334      * @param   msg     The string message (or a key in the message catalog)
1335      */
1336     public void config(String msg) {
1337         if (Level.CONFIG.intValue() < levelValue) {
1338             return;
1339         }
1340         log(Level.CONFIG, msg);
1341     }
1342 
1343     /**
1344      * Log a FINE message.
1345      * <p>
1346      * If the logger is currently enabled for the FINE message
1347      * level then the given message is forwarded to all the
1348      * registered output Handler objects.
1349      * <p>
1350      * @param   msg     The string message (or a key in the message catalog)
1351      */
1352     public void fine(String msg) {
1353         if (Level.FINE.intValue() < levelValue) {
1354             return;
1355         }
1356         log(Level.FINE, msg);
1357     }
1358 
1359     /**
1360      * Log a FINER message.
1361      * <p>
1362      * If the logger is currently enabled for the FINER message
1363      * level then the given message is forwarded to all the
1364      * registered output Handler objects.
1365      * <p>
1366      * @param   msg     The string message (or a key in the message catalog)
1367      */
1368     public void finer(String msg) {
1369         if (Level.FINER.intValue() < levelValue) {
1370             return;
1371         }
1372         log(Level.FINER, msg);
1373     }
1374 
1375     /**
1376      * Log a FINEST message.
1377      * <p>
1378      * If the logger is currently enabled for the FINEST message
1379      * level then the given message is forwarded to all the
1380      * registered output Handler objects.
1381      * <p>
1382      * @param   msg     The string message (or a key in the message catalog)
1383      */
1384     public void finest(String msg) {
1385         if (Level.FINEST.intValue() < levelValue) {
1386             return;
1387         }
1388         log(Level.FINEST, msg);
1389     }
1390 
1391     //=======================================================================
1392     // Start of simple convenience methods using level names as method names
1393     // and use Supplier<String>
1394     //=======================================================================
1395 
1396     /**
1397      * Log a SEVERE message, which is only to be constructed if the logging
1398      * level is such that the message will actually be logged.
1399      * <p>
1400      * If the logger is currently enabled for the SEVERE message
1401      * level then the message is constructed by invoking the provided
1402      * supplier function and forwarded to all the registered output
1403      * Handler objects.
1404      * <p>
1405      * @param   msgSupplier   A function, which when called, produces the
1406      *                        desired log message
1407      * @since   1.8
1408      */
1409     public void severe(Supplier<String> msgSupplier) {
1410         log(Level.SEVERE, msgSupplier);
1411     }
1412 
1413     /**
1414      * Log a WARNING message, which is only to be constructed if the logging
1415      * level is such that the message will actually be logged.
1416      * <p>
1417      * If the logger is currently enabled for the WARNING message
1418      * level then the message is constructed by invoking the provided
1419      * supplier function and forwarded to all the registered output
1420      * Handler objects.
1421      * <p>
1422      * @param   msgSupplier   A function, which when called, produces the
1423      *                        desired log message
1424      * @since   1.8
1425      */
1426     public void warning(Supplier<String> msgSupplier) {
1427         log(Level.WARNING, msgSupplier);
1428     }
1429 
1430     /**
1431      * Log a INFO message, which is only to be constructed if the logging
1432      * level is such that the message will actually be logged.
1433      * <p>
1434      * If the logger is currently enabled for the INFO message
1435      * level then the message is constructed by invoking the provided
1436      * supplier function and forwarded to all the registered output
1437      * Handler objects.
1438      * <p>
1439      * @param   msgSupplier   A function, which when called, produces the
1440      *                        desired log message
1441      * @since   1.8
1442      */
1443     public void info(Supplier<String> msgSupplier) {
1444         log(Level.INFO, msgSupplier);
1445     }
1446 
1447     /**
1448      * Log a CONFIG message, which is only to be constructed if the logging
1449      * level is such that the message will actually be logged.
1450      * <p>
1451      * If the logger is currently enabled for the CONFIG message
1452      * level then the message is constructed by invoking the provided
1453      * supplier function and forwarded to all the registered output
1454      * Handler objects.
1455      * <p>
1456      * @param   msgSupplier   A function, which when called, produces the
1457      *                        desired log message
1458      * @since   1.8
1459      */
1460     public void config(Supplier<String> msgSupplier) {
1461         log(Level.CONFIG, msgSupplier);
1462     }
1463 
1464     /**
1465      * Log a FINE message, which is only to be constructed if the logging
1466      * level is such that the message will actually be logged.
1467      * <p>
1468      * If the logger is currently enabled for the FINE message
1469      * level then the message is constructed by invoking the provided
1470      * supplier function and forwarded to all the registered output
1471      * Handler objects.
1472      * <p>
1473      * @param   msgSupplier   A function, which when called, produces the
1474      *                        desired log message
1475      * @since   1.8
1476      */
1477     public void fine(Supplier<String> msgSupplier) {
1478         log(Level.FINE, msgSupplier);
1479     }
1480 
1481     /**
1482      * Log a FINER message, which is only to be constructed if the logging
1483      * level is such that the message will actually be logged.
1484      * <p>
1485      * If the logger is currently enabled for the FINER message
1486      * level then the message is constructed by invoking the provided
1487      * supplier function and forwarded to all the registered output
1488      * Handler objects.
1489      * <p>
1490      * @param   msgSupplier   A function, which when called, produces the
1491      *                        desired log message
1492      * @since   1.8
1493      */
1494     public void finer(Supplier<String> msgSupplier) {
1495         log(Level.FINER, msgSupplier);
1496     }
1497 
1498     /**
1499      * Log a FINEST message, which is only to be constructed if the logging
1500      * level is such that the message will actually be logged.
1501      * <p>
1502      * If the logger is currently enabled for the FINEST message
1503      * level then the message is constructed by invoking the provided
1504      * supplier function and forwarded to all the registered output
1505      * Handler objects.
1506      * <p>
1507      * @param   msgSupplier   A function, which when called, produces the
1508      *                        desired log message
1509      * @since   1.8
1510      */
1511     public void finest(Supplier<String> msgSupplier) {
1512         log(Level.FINEST, msgSupplier);
1513     }
1514 
1515     //================================================================
1516     // End of convenience methods
1517     //================================================================
1518 
1519     /**
1520      * Set the log level specifying which message levels will be
1521      * logged by this logger.  Message levels lower than this
1522      * value will be discarded.  The level value Level.OFF
1523      * can be used to turn off logging.
1524      * <p>
1525      * If the new level is null, it means that this node should
1526      * inherit its level from its nearest ancestor with a specific
1527      * (non-null) level value.
1528      *
1529      * @param newLevel   the new value for the log level (may be null)
1530      * @exception  SecurityException  if a security manager exists and if
1531      *             the caller does not have LoggingPermission("control").
1532      */
1533     public void setLevel(Level newLevel) throws SecurityException {
1534         checkPermission();
1535         synchronized (treeLock) {
1536             levelObject = newLevel;
1537             updateEffectiveLevel();
1538         }
1539     }
1540 
1541     /**
1542      * Get the log Level that has been specified for this Logger.
1543      * The result may be null, which means that this logger's
1544      * effective level will be inherited from its parent.
1545      *
1546      * @return  this Logger's level
1547      */
1548     public Level getLevel() {
1549         return levelObject;
1550     }
1551 
1552     /**
1553      * Check if a message of the given level would actually be logged
1554      * by this logger.  This check is based on the Loggers effective level,
1555      * which may be inherited from its parent.
1556      *
1557      * @param   level   a message logging level
1558      * @return  true if the given message level is currently being logged.
1559      */
1560     public boolean isLoggable(Level level) {
1561         if (level.intValue() < levelValue || levelValue == offValue) {
1562             return false;
1563         }
1564         return true;
1565     }
1566 
1567     /**
1568      * Get the name for this logger.
1569      * @return logger name.  Will be null for anonymous Loggers.
1570      */
1571     public String getName() {
1572         return name;
1573     }
1574 
1575     /**
1576      * Add a log Handler to receive logging messages.
1577      * <p>
1578      * By default, Loggers also send their output to their parent logger.
1579      * Typically the root Logger is configured with a set of Handlers
1580      * that essentially act as default handlers for all loggers.
1581      *
1582      * @param   handler a logging Handler
1583      * @exception  SecurityException  if a security manager exists and if
1584      *             the caller does not have LoggingPermission("control").
1585      */
1586     public void addHandler(Handler handler) throws SecurityException {
1587         // Check for null handler
1588         handler.getClass();
1589         checkPermission();
1590         handlers.add(handler);
1591     }
1592 
1593     /**
1594      * Remove a log Handler.
1595      * <P>
1596      * Returns silently if the given Handler is not found or is null
1597      *
1598      * @param   handler a logging Handler
1599      * @exception  SecurityException  if a security manager exists and if
1600      *             the caller does not have LoggingPermission("control").
1601      */
1602     public void removeHandler(Handler handler) throws SecurityException {
1603         checkPermission();
1604         if (handler == null) {
1605             return;
1606         }
1607         handlers.remove(handler);
1608     }
1609 
1610     /**
1611      * Get the Handlers associated with this logger.
1612      * <p>
1613      * @return  an array of all registered Handlers
1614      */
1615     public Handler[] getHandlers() {
1616         return handlers.toArray(emptyHandlers);
1617     }
1618 
1619     /**
1620      * Specify whether or not this logger should send its output
1621      * to its parent Logger.  This means that any LogRecords will
1622      * also be written to the parent's Handlers, and potentially
1623      * to its parent, recursively up the namespace.
1624      *
1625      * @param useParentHandlers   true if output is to be sent to the
1626      *          logger's parent.
1627      * @exception  SecurityException  if a security manager exists and if
1628      *             the caller does not have LoggingPermission("control").
1629      */
1630     public void setUseParentHandlers(boolean useParentHandlers) {
1631         checkPermission();
1632         this.useParentHandlers = useParentHandlers;
1633     }
1634 
1635     /**
1636      * Discover whether or not this logger is sending its output
1637      * to its parent logger.
1638      *
1639      * @return  true if output is to be sent to the logger's parent
1640      */
1641     public boolean getUseParentHandlers() {
1642         return useParentHandlers;
1643     }
1644 
1645     static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging";
1646 
1647     private static ResourceBundle findSystemResourceBundle(final Locale locale) {
1648         // the resource bundle is in a restricted package
1649         return AccessController.doPrivileged(new PrivilegedAction<ResourceBundle>() {
1650             public ResourceBundle run() {
1651                 try {
1652                     return ResourceBundle.getBundle(SYSTEM_LOGGER_RB_NAME,
1653                                                     locale,
1654                                                     ClassLoader.getSystemClassLoader());
1655                 } catch (MissingResourceException e) {
1656                     throw new InternalError(e.toString());
1657                 }
1658             }
1659         });
1660     }
1661 
1662     /**
1663      * Private utility method to map a resource bundle name to an
1664      * actual resource bundle, using a simple one-entry cache.
1665      * Returns null for a null name.
1666      * May also return null if we can't find the resource bundle and
1667      * there is no suitable previous cached value.
1668      *
1669      * @param name the ResourceBundle to locate
1670      * @param userCallersClassLoader if true search using the caller's ClassLoader
1671      * @return ResourceBundle specified by name or null if not found
1672      */
1673     private synchronized ResourceBundle findResourceBundle(String name,
1674                                                            boolean useCallersClassLoader) {
1675         // For all lookups, we first check the thread context class loader
1676         // if it is set.  If not, we use the system classloader.  If we
1677         // still haven't found it we use the callersClassLoaderRef if it
1678         // is set and useCallersClassLoader is true.  We set
1679         // callersClassLoaderRef initially upon creating the logger with a
1680         // non-null resource bundle name.
1681 
1682         // Return a null bundle for a null name.
1683         if (name == null) {
1684             return null;
1685         }
1686 
1687         Locale currentLocale = Locale.getDefault();
1688 
1689         // Normally we should hit on our simple one entry cache.
1690         if (catalog != null && currentLocale.equals(catalogLocale)
1691                 && name.equals(catalogName)) {
1692             return catalog;
1693         }
1694 
1695         if (name.equals(SYSTEM_LOGGER_RB_NAME)) {
1696             catalog = findSystemResourceBundle(currentLocale);
1697             catalogName = name;
1698             catalogLocale = currentLocale;
1699             return catalog;
1700         }
1701 
1702         // Use the thread's context ClassLoader.  If there isn't one, use the
1703         // {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader}.
1704         ClassLoader cl = Thread.currentThread().getContextClassLoader();
1705         if (cl == null) {
1706             cl = ClassLoader.getSystemClassLoader();
1707         }
1708         try {
1709             catalog = ResourceBundle.getBundle(name, currentLocale, cl);
1710             catalogName = name;
1711             catalogLocale = currentLocale;
1712             return catalog;
1713         } catch (MissingResourceException ex) {
1714             // We can't find the ResourceBundle in the default
1715             // ClassLoader.  Drop through.
1716         }
1717 
1718         if (useCallersClassLoader) {
1719             // Try with the caller's ClassLoader
1720             ClassLoader callersClassLoader = getCallersClassLoader();
1721 
1722             if (callersClassLoader == null || callersClassLoader == cl) {
1723                 return null;
1724             }
1725 
1726             try {
1727                 catalog = ResourceBundle.getBundle(name, currentLocale,
1728                                                    callersClassLoader);
1729                 catalogName = name;
1730                 catalogLocale = currentLocale;
1731                 return catalog;
1732             } catch (MissingResourceException ex) {
1733                 return null; // no luck
1734             }
1735         } else {
1736             return null;
1737         }
1738     }
1739 
1740     // Private utility method to initialize our one entry
1741     // resource bundle name cache and the callers ClassLoader
1742     // Note: for consistency reasons, we are careful to check
1743     // that a suitable ResourceBundle exists before setting the
1744     // resourceBundleName field.
1745     // Synchronized to prevent races in setting the fields.
1746     private synchronized void setupResourceInfo(String name,
1747                                                 Class<?> callersClass) {
1748         if (resourceBundleName != null) {
1749             // this Logger already has a ResourceBundle
1750 
1751             if (resourceBundleName.equals(name)) {
1752                 // the names match so there is nothing more to do
1753                 return;
1754             }
1755 
1756             // cannot change ResourceBundles once they are set
1757             throw new IllegalArgumentException(
1758                 resourceBundleName + " != " + name);
1759         }
1760 
1761         if (name == null) {
1762             return;
1763         }
1764 
1765         setCallersClassLoaderRef(callersClass);
1766         if (findResourceBundle(name, true) == null) {
1767             // We've failed to find an expected ResourceBundle.
1768             // unset the caller's ClassLoader since we were unable to find the
1769             // the bundle using it
1770             this.callersClassLoaderRef = null;
1771             throw new MissingResourceException("Can't find " + name + " bundle",
1772                                                 name, "");
1773         }
1774         resourceBundleName = name;
1775     }
1776 
1777     /**
1778      * Return the parent for this Logger.
1779      * <p>
1780      * This method returns the nearest extant parent in the namespace.
1781      * Thus if a Logger is called "a.b.c.d", and a Logger called "a.b"
1782      * has been created but no logger "a.b.c" exists, then a call of
1783      * getParent on the Logger "a.b.c.d" will return the Logger "a.b".
1784      * <p>
1785      * The result will be null if it is called on the root Logger
1786      * in the namespace.
1787      *
1788      * @return nearest existing parent Logger
1789      */
1790     public Logger getParent() {
1791         // Note: this used to be synchronized on treeLock.  However, this only
1792         // provided memory semantics, as there was no guarantee that the caller
1793         // would synchronize on treeLock (in fact, there is no way for external
1794         // callers to so synchronize).  Therefore, we have made parent volatile
1795         // instead.
1796         return parent;
1797     }
1798 
1799     /**
1800      * Set the parent for this Logger.  This method is used by
1801      * the LogManager to update a Logger when the namespace changes.
1802      * <p>
1803      * It should not be called from application code.
1804      * <p>
1805      * @param  parent   the new parent logger
1806      * @exception  SecurityException  if a security manager exists and if
1807      *             the caller does not have LoggingPermission("control").
1808      */
1809     public void setParent(Logger parent) {
1810         if (parent == null) {
1811             throw new NullPointerException();
1812         }
1813         checkPermission();
1814         doSetParent(parent);
1815     }
1816 
1817     // Private method to do the work for parenting a child
1818     // Logger onto a parent logger.
1819     private void doSetParent(Logger newParent) {
1820 
1821         // System.err.println("doSetParent \"" + getName() + "\" \""
1822         //                              + newParent.getName() + "\"");
1823 
1824         synchronized (treeLock) {
1825 
1826             // Remove ourself from any previous parent.
1827             LogManager.LoggerWeakRef ref = null;
1828             if (parent != null) {
1829                 // assert parent.kids != null;
1830                 for (Iterator<LogManager.LoggerWeakRef> iter = parent.kids.iterator(); iter.hasNext(); ) {
1831                     ref = iter.next();
1832                     Logger kid =  ref.get();
1833                     if (kid == this) {
1834                         // ref is used down below to complete the reparenting
1835                         iter.remove();
1836                         break;
1837                     } else {
1838                         ref = null;
1839                     }
1840                 }
1841                 // We have now removed ourself from our parents' kids.
1842             }
1843 
1844             // Set our new parent.
1845             parent = newParent;
1846             if (parent.kids == null) {
1847                 parent.kids = new ArrayList<>(2);
1848             }
1849             if (ref == null) {
1850                 // we didn't have a previous parent
1851                 ref = manager.new LoggerWeakRef(this);
1852             }
1853             ref.setParentRef(new WeakReference<Logger>(parent));
1854             parent.kids.add(ref);
1855 
1856             // As a result of the reparenting, the effective level
1857             // may have changed for us and our children.
1858             updateEffectiveLevel();
1859 
1860         }
1861     }
1862 
1863     // Package-level method.
1864     // Remove the weak reference for the specified child Logger from the
1865     // kid list. We should only be called from LoggerWeakRef.dispose().
1866     final void removeChildLogger(LogManager.LoggerWeakRef child) {
1867         synchronized (treeLock) {
1868             for (Iterator<LogManager.LoggerWeakRef> iter = kids.iterator(); iter.hasNext(); ) {
1869                 LogManager.LoggerWeakRef ref = iter.next();
1870                 if (ref == child) {
1871                     iter.remove();
1872                     return;
1873                 }
1874             }
1875         }
1876     }
1877 
1878     // Recalculate the effective level for this node and
1879     // recursively for our children.
1880 
1881     private void updateEffectiveLevel() {
1882         // assert Thread.holdsLock(treeLock);
1883 
1884         // Figure out our current effective level.
1885         int newLevelValue;
1886         if (levelObject != null) {
1887             newLevelValue = levelObject.intValue();
1888         } else {
1889             if (parent != null) {
1890                 newLevelValue = parent.levelValue;
1891             } else {
1892                 // This may happen during initialization.
1893                 newLevelValue = Level.INFO.intValue();
1894             }
1895         }
1896 
1897         // If our effective value hasn't changed, we're done.
1898         if (levelValue == newLevelValue) {
1899             return;
1900         }
1901 
1902         levelValue = newLevelValue;
1903 
1904         // System.err.println("effective level: \"" + getName() + "\" := " + level);
1905 
1906         // Recursively update the level on each of our kids.
1907         if (kids != null) {
1908             for (int i = 0; i < kids.size(); i++) {
1909                 LogManager.LoggerWeakRef ref = kids.get(i);
1910                 Logger kid =  ref.get();
1911                 if (kid != null) {
1912                     kid.updateEffectiveLevel();
1913                 }
1914             }
1915         }
1916     }
1917 
1918 
1919     // Private method to get the potentially inherited
1920     // resource bundle name for this Logger.
1921     // May return null
1922     private String getEffectiveResourceBundleName() {
1923         Logger target = this;
1924         while (target != null) {
1925             String rbn = target.getResourceBundleName();
1926             if (rbn != null) {
1927                 return rbn;
1928             }
1929             target = target.getParent();
1930         }
1931         return null;
1932     }
1933 
1934 
1935 }