1 /*
   2  * Copyright (c) 2000, 2021, 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 package java.util.logging;
  27 
  28 import java.lang.ref.WeakReference;
  29 import java.security.AccessController;
  30 import java.security.PrivilegedAction;
  31 import java.util.ArrayList;
  32 import java.util.Iterator;
  33 import java.util.Locale;
  34 import java.util.MissingResourceException;
  35 import java.util.Objects;
  36 import java.util.ResourceBundle;
  37 import java.util.concurrent.CopyOnWriteArrayList;
  38 import java.util.function.Supplier;
  39 
  40 import jdk.internal.access.JavaUtilResourceBundleAccess;
  41 import jdk.internal.access.SharedSecrets;
  42 import jdk.internal.reflect.CallerSensitive;
  43 import jdk.internal.reflect.CallerSensitiveAdapter;
  44 import jdk.internal.reflect.Reflection;
  45 import static jdk.internal.logger.DefaultLoggerFinder.isSystem;
  46 
  47 /**
  48  * A Logger object is used to log messages for a specific
  49  * system or application component.  Loggers are normally named,
  50  * using a hierarchical dot-separated namespace.  Logger names
  51  * can be arbitrary strings, but they should normally be based on
  52  * the package name or class name of the logged component, such
  53  * as java.net or javax.swing.  In addition it is possible to create
  54  * "anonymous" Loggers that are not stored in the Logger namespace.
  55  * <p>
  56  * Logger objects may be obtained by calls on one of the getLogger
  57  * factory methods.  These will either create a new Logger or
  58  * return a suitable existing Logger. It is important to note that
  59  * the Logger returned by one of the {@code getLogger} factory methods
  60  * may be garbage collected at any time if a strong reference to the
  61  * Logger is not kept.
  62  * <p>
  63  * Logging messages will be forwarded to registered Handler
  64  * objects, which can forward the messages to a variety of
  65  * destinations, including consoles, files, OS logs, etc.
  66  * <p>
  67  * Each Logger keeps track of a "parent" Logger, which is its
  68  * nearest existing ancestor in the Logger namespace.
  69  * <p>
  70  * Each Logger has a "Level" associated with it.  This reflects
  71  * a minimum Level that this logger cares about.  If a Logger's
  72  * level is set to {@code null}, then its effective level is inherited
  73  * from its parent, which may in turn obtain it recursively from its
  74  * parent, and so on up the tree.
  75  * <p>
  76  * The log level can be configured based on the properties from the
  77  * logging configuration file, as described in the description
  78  * of the LogManager class.  However it may also be dynamically changed
  79  * by calls on the Logger.setLevel method.  If a logger's level is
  80  * changed the change may also affect child loggers, since any child
  81  * logger that has {@code null} as its level will inherit its
  82  * effective level from its parent.
  83  * <p>
  84  * On each logging call the Logger initially performs a cheap
  85  * check of the request level (e.g., SEVERE or FINE) against the
  86  * effective log level of the logger.  If the request level is
  87  * lower than the log level, the logging call returns immediately.
  88  * <p>
  89  * After passing this initial (cheap) test, the Logger will allocate
  90  * a LogRecord to describe the logging message.  It will then call a
  91  * Filter (if present) to do a more detailed check on whether the
  92  * record should be published.  If that passes it will then publish
  93  * the LogRecord to its output Handlers.  By default, loggers also
  94  * publish to their parent's Handlers, recursively up the tree.
  95  * <p>
  96  * Each Logger may have a {@code ResourceBundle} associated with it.
  97  * The {@code ResourceBundle} may be specified by name, using the
  98  * {@link #getLogger(java.lang.String, java.lang.String)} factory
  99  * method, or by value - using the {@link
 100  * #setResourceBundle(java.util.ResourceBundle) setResourceBundle} method.
 101  * This bundle will be used for localizing logging messages.
 102  * If a Logger does not have its own {@code ResourceBundle} or resource bundle
 103  * name, then it will inherit the {@code ResourceBundle} or resource bundle name
 104  * from its parent, recursively up the tree.
 105  * <p>
 106  * Most of the logger output methods take a "msg" argument.  This
 107  * msg argument may be either a raw value or a localization key.
 108  * During formatting, if the logger has (or inherits) a localization
 109  * {@code ResourceBundle} and if the {@code ResourceBundle} has a mapping for
 110  * the msg string, then the msg string is replaced by the localized value.
 111  * Otherwise the original msg string is used.  Typically, formatters use
 112  * java.text.MessageFormat style formatting to format parameters, so
 113  * for example a format string "{0} {1}" would format two parameters
 114  * as strings.
 115  * <p>
 116  * A set of methods alternatively take a "msgSupplier" instead of a "msg"
 117  * argument.  These methods take a {@link Supplier}{@code <String>} function
 118  * which is invoked to construct the desired log message only when the message
 119  * actually is to be logged based on the effective log level thus eliminating
 120  * unnecessary message construction. For example, if the developer wants to
 121  * log system health status for diagnosis, with the String-accepting version,
 122  * the code would look like:
 123  * <pre>{@code
 124  *
 125  *  class DiagnosisMessages {
 126  *    static String systemHealthStatus() {
 127  *      // collect system health information
 128  *      ...
 129  *    }
 130  *  }
 131  *  ...
 132  *  logger.log(Level.FINER, DiagnosisMessages.systemHealthStatus());
 133  * }</pre>
 134  * With the above code, the health status is collected unnecessarily even when
 135  * the log level FINER is disabled. With the Supplier-accepting version as
 136  * below, the status will only be collected when the log level FINER is
 137  * enabled.
 138  * <pre>{@code
 139  *
 140  *  logger.log(Level.FINER, DiagnosisMessages::systemHealthStatus);
 141  * }</pre>
 142  * <p>
 143  * When looking for a {@code ResourceBundle}, the logger will first look at
 144  * whether a bundle was specified using {@link
 145  * #setResourceBundle(java.util.ResourceBundle) setResourceBundle}, and then
 146  * only whether a resource bundle name was specified through the {@link
 147  * #getLogger(java.lang.String, java.lang.String) getLogger} factory method.
 148  * If no {@code ResourceBundle} or no resource bundle name is found,
 149  * then it will use the nearest {@code ResourceBundle} or resource bundle
 150  * name inherited from its parent tree.<br>
 151  * When a {@code ResourceBundle} was inherited or specified through the
 152  * {@link
 153  * #setResourceBundle(java.util.ResourceBundle) setResourceBundle} method, then
 154  * that {@code ResourceBundle} will be used. Otherwise if the logger only
 155  * has or inherited a resource bundle name, then that resource bundle name
 156  * will be mapped to a {@code ResourceBundle} object, using the default Locale
 157  * at the time of logging.
 158  * <br id="ResourceBundleMapping">When mapping resource bundle names to
 159  * {@code ResourceBundle} objects, the logger will first try to use the
 160  * Thread's {@linkplain java.lang.Thread#getContextClassLoader() context class
 161  * loader} to map the given resource bundle name to a {@code ResourceBundle}.
 162  * If the thread context class loader is {@code null}, it will try the
 163  * {@linkplain java.lang.ClassLoader#getSystemClassLoader() system class loader}
 164  * instead.  If the {@code ResourceBundle} is still not found, it will use the
 165  * class loader of the first caller of the {@link
 166  * #getLogger(java.lang.String, java.lang.String) getLogger} factory method.
 167  * <p>
 168  * Formatting (including localization) is the responsibility of
 169  * the output Handler, which will typically call a Formatter.
 170  * <p>
 171  * Note that formatting need not occur synchronously.  It may be delayed
 172  * until a LogRecord is actually written to an external sink.
 173  * <p>
 174  * The logging methods are grouped in five main categories:
 175  * <ul>
 176  * <li><p>
 177  *     There are a set of "log" methods that take a log level, a message
 178  *     string, and optionally some parameters to the message string.
 179  * <li><p>
 180  *     There are a set of "logp" methods (for "log precise") that are
 181  *     like the "log" methods, but also take an explicit source class name
 182  *     and method name.
 183  * <li><p>
 184  *     There are a set of "logrb" method (for "log with resource bundle")
 185  *     that are like the "logp" method, but also take an explicit resource
 186  *     bundle object for use in localizing the log message.
 187  * <li><p>
 188  *     There are convenience methods for tracing method entries (the
 189  *     "entering" methods), method returns (the "exiting" methods) and
 190  *     throwing exceptions (the "throwing" methods).
 191  * <li><p>
 192  *     Finally, there are a set of convenience methods for use in the
 193  *     very simplest cases, when a developer simply wants to log a
 194  *     simple string at a given log level.  These methods are named
 195  *     after the standard Level names ("severe", "warning", "info", etc.)
 196  *     and take a single argument, a message string.
 197  * </ul>
 198  * <p>
 199  * For the methods that do not take an explicit source name and
 200  * method name, the Logging framework will make a "best effort"
 201  * to determine which class and method called into the logging method.
 202  * However, it is important to realize that this automatically inferred
 203  * information may only be approximate (or may even be quite wrong!).
 204  * Virtual machines are allowed to do extensive optimizations when
 205  * JITing and may entirely remove stack frames, making it impossible
 206  * to reliably locate the calling class and method.
 207  * <P>
 208  * All methods on Logger are multi-thread safe.
 209  * <p>
 210  * <b>Subclassing Information:</b> Note that a LogManager class may
 211  * provide its own implementation of named Loggers for any point in
 212  * the namespace.  Therefore, any subclasses of Logger (unless they
 213  * are implemented in conjunction with a new LogManager class) should
 214  * take care to obtain a Logger instance from the LogManager class and
 215  * should delegate operations such as "isLoggable" and "log(LogRecord)"
 216  * to that instance.  Note that in order to intercept all logging
 217  * output, subclasses need only override the log(LogRecord) method.
 218  * All the other logging methods are implemented as calls on this
 219  * log(LogRecord) method.
 220  *
 221  * @since 1.4
 222  */
 223 public class Logger {
 224     private static final Handler emptyHandlers[] = new Handler[0];
 225     private static final int offValue = Level.OFF.intValue();
 226 
 227     static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging";
 228 
 229     // This class is immutable and it is important that it remains so.
 230     private static final class LoggerBundle {
 231         final String resourceBundleName; // Base name of the bundle.
 232         final ResourceBundle userBundle; // Bundle set through setResourceBundle.
 233         private LoggerBundle(String resourceBundleName, ResourceBundle bundle) {
 234             this.resourceBundleName = resourceBundleName;
 235             this.userBundle = bundle;
 236         }
 237         boolean isSystemBundle() {
 238             return SYSTEM_LOGGER_RB_NAME.equals(resourceBundleName);
 239         }
 240         static LoggerBundle get(String name, ResourceBundle bundle) {
 241             if (name == null && bundle == null) {
 242                 return NO_RESOURCE_BUNDLE;
 243             } else if (SYSTEM_LOGGER_RB_NAME.equals(name) && bundle == null) {
 244                 return SYSTEM_BUNDLE;
 245             } else {
 246                 return new LoggerBundle(name, bundle);
 247             }
 248         }
 249     }
 250 
 251     // This instance will be shared by all loggers created by the system
 252     // code
 253     private static final LoggerBundle SYSTEM_BUNDLE =
 254             new LoggerBundle(SYSTEM_LOGGER_RB_NAME, null);
 255 
 256     // This instance indicates that no resource bundle has been specified yet,
 257     // and it will be shared by all loggers which have no resource bundle.
 258     private static final LoggerBundle NO_RESOURCE_BUNDLE =
 259             new LoggerBundle(null, null);
 260 
 261     // Calling SharedSecrets.getJavaUtilResourceBundleAccess()
 262     // forces the initialization of ResourceBundle.class, which
 263     // can be too early if the VM has not finished booting yet.
 264     private static final class RbAccess {
 265         static final JavaUtilResourceBundleAccess RB_ACCESS =
 266             SharedSecrets.getJavaUtilResourceBundleAccess();
 267     }
 268 
 269     // A value class that holds the logger configuration data.
 270     // This configuration can be shared between an application logger
 271     // and a system logger of the same name.
 272     private static final class ConfigurationData {
 273 
 274         // The delegate field is used to avoid races while
 275         // merging configuration. This will ensure that any pending
 276         // configuration action on an application logger will either
 277         // be finished before the merge happens, or will be forwarded
 278         // to the system logger configuration after the merge is completed.
 279         // By default delegate=this.
 280         private volatile ConfigurationData delegate;
 281 
 282         volatile boolean useParentHandlers;
 283         volatile Filter filter;
 284         volatile Level levelObject;
 285         volatile int levelValue;  // current effective level value
 286         final CopyOnWriteArrayList<Handler> handlers =
 287             new CopyOnWriteArrayList<>();
 288 
 289         ConfigurationData() {
 290             delegate = this;
 291             useParentHandlers = true;
 292             levelValue = Level.INFO.intValue();
 293         }
 294 
 295         void setUseParentHandlers(boolean flag) {
 296             useParentHandlers = flag;
 297             if (delegate != this) {
 298                 // merge in progress - propagate value to system peer.
 299                 final ConfigurationData system = delegate;
 300                 synchronized (system) {
 301                     system.useParentHandlers = useParentHandlers;
 302                 }
 303             }
 304         }
 305 
 306         void setFilter(Filter f) {
 307             filter = f;
 308             if (delegate != this) {
 309                 // merge in progress - propagate value to system peer.
 310                 final ConfigurationData system = delegate;
 311                 synchronized (system) {
 312                     system.filter = filter;
 313                 }
 314             }
 315         }
 316 
 317         void setLevelObject(Level l) {
 318             levelObject = l;
 319             if (delegate != this) {
 320                 // merge in progress - propagate value to system peer.
 321                 final ConfigurationData system = delegate;
 322                 synchronized (system) {
 323                     system.levelObject = levelObject;
 324                 }
 325             }
 326         }
 327 
 328         void setLevelValue(int v) {
 329             levelValue = v;
 330             if (delegate != this) {
 331                 // merge in progress - propagate value to system peer.
 332                 final ConfigurationData system = delegate;
 333                 synchronized (system) {
 334                     system.levelValue = levelValue;
 335                 }
 336             }
 337         }
 338 
 339         void addHandler(Handler h) {
 340             if (handlers.add(h)) {
 341                 if (delegate != this) {
 342                     // merge in progress - propagate value to system peer.
 343                     final ConfigurationData system = delegate;
 344                     synchronized (system) {
 345                         system.handlers.addIfAbsent(h);
 346                     }
 347                 }
 348             }
 349         }
 350 
 351         void removeHandler(Handler h) {
 352             if (handlers.remove(h)) {
 353                 if (delegate != this) {
 354                     // merge in progress - propagate value to system peer.
 355                     final ConfigurationData system = delegate;
 356                     synchronized (system) {
 357                         system.handlers.remove(h);
 358                     }
 359                 }
 360             }
 361         }
 362 
 363         ConfigurationData merge(Logger systemPeer) {
 364             if (!systemPeer.isSystemLogger) {
 365                 // should never come here
 366                 throw new InternalError("not a system logger");
 367             }
 368 
 369             ConfigurationData system = systemPeer.config;
 370 
 371             if (system == this) {
 372                 // nothing to do
 373                 return system;
 374             }
 375 
 376             synchronized (system) {
 377                 // synchronize before checking on delegate to counter
 378                 // race conditions where two threads might attempt to
 379                 // merge concurrently
 380                 if (delegate == system) {
 381                     // merge already performed;
 382                     return system;
 383                 }
 384 
 385                 // publish system as the temporary delegate configuration.
 386                 // This should take care of potential race conditions where
 387                 // an other thread might attempt to call e.g. setlevel on
 388                 // the application logger while merge is in progress.
 389                 // (see implementation of ConfigurationData::setLevel)
 390                 delegate = system;
 391 
 392                 // merge this config object data into the system config
 393                 system.useParentHandlers = useParentHandlers;
 394                 system.filter = filter;
 395                 system.levelObject = levelObject;
 396                 system.levelValue = levelValue;
 397 
 398                 // Prevent race condition in case two threads attempt to merge
 399                 // configuration and add handlers at the same time. We don't want
 400                 // to add the same handlers twice.
 401                 //
 402                 // Handlers are created and loaded by LogManager.addLogger. If we
 403                 // reach here, then it means that the application logger has
 404                 // been created first and added with LogManager.addLogger, and the
 405                 // system logger was created after - and no handler has been added
 406                 // to it by LogManager.addLogger. Therefore, system.handlers
 407                 // should be empty.
 408                 //
 409                 // A non empty cfg.handlers list indicates a race condition
 410                 // where two threads might attempt to merge the configuration
 411                 // or add handlers concurrently. Though of no consequence for
 412                 // the other data (level etc...) this would be an issue if we
 413                 // added the same handlers twice.
 414                 //
 415                 for (Handler h : handlers) {
 416                     if (!system.handlers.contains(h)) {
 417                         systemPeer.addHandler(h);
 418                     }
 419                 }
 420                 system.handlers.retainAll(handlers);
 421                 system.handlers.addAllAbsent(handlers);
 422             }
 423 
 424             // sanity: update effective level after merging
 425             synchronized(treeLock) {
 426                 systemPeer.updateEffectiveLevel();
 427             }
 428 
 429             return system;
 430         }
 431 
 432     }
 433 
 434     // The logger configuration data. Ideally, this should be final
 435     // for system loggers, and replace-once for application loggers.
 436     // When an application requests a logger by name, we do not know a-priori
 437     // whether that corresponds to a system logger name or not.
 438     // So if no system logger by that name already exists, we simply return an
 439     // application logger.
 440     // If a system class later requests a system logger of the same name, then
 441     // the application logger and system logger configurations will be merged
 442     // in a single instance of ConfigurationData that both loggers will share.
 443     private volatile ConfigurationData config;
 444 
 445     private volatile LogManager manager;
 446     private String name;
 447     private volatile LoggerBundle loggerBundle = NO_RESOURCE_BUNDLE;
 448     private boolean anonymous;
 449 
 450     // Cache to speed up behavior of findResourceBundle:
 451     private WeakReference<ResourceBundle> catalogRef;  // Cached resource bundle
 452     private String catalogName;         // name associated with catalog
 453     private Locale catalogLocale;       // locale associated with catalog
 454 
 455     // The fields relating to parent-child relationships and levels
 456     // are managed under a separate lock, the treeLock.
 457     private static final Object treeLock = new Object();
 458     // We keep weak references from parents to children, but strong
 459     // references from children to parents.
 460     private volatile Logger parent;    // our nearest parent.
 461     private ArrayList<LogManager.LoggerWeakRef> kids;   // WeakReferences to loggers that have us as parent
 462     private WeakReference<Module> callerModuleRef;
 463     private final boolean isSystemLogger;
 464 
 465     /**
 466      * GLOBAL_LOGGER_NAME is a name for the global logger.
 467      *
 468      * @since 1.6
 469      */
 470     public static final String GLOBAL_LOGGER_NAME = "global";
 471 
 472     /**
 473      * Return global logger object with the name Logger.GLOBAL_LOGGER_NAME.
 474      *
 475      * @return global logger object
 476      * @since 1.7
 477      */
 478     public static final Logger getGlobal() {
 479         // In order to break a cyclic dependence between the LogManager
 480         // and Logger static initializers causing deadlocks, the global
 481         // logger is created with a special constructor that does not
 482         // initialize its log manager.
 483         //
 484         // If an application calls Logger.getGlobal() before any logger
 485         // has been initialized, it is therefore possible that the
 486         // LogManager class has not been initialized yet, and therefore
 487         // Logger.global.manager will be null.
 488         //
 489         // In order to finish the initialization of the global logger, we
 490         // will therefore call LogManager.getLogManager() here.
 491         //
 492         // To prevent race conditions we also need to call
 493         // LogManager.getLogManager() unconditionally here.
 494         // Indeed we cannot rely on the observed value of global.manager,
 495         // because global.manager will become not null somewhere during
 496         // the initialization of LogManager.
 497         // If two threads are calling getGlobal() concurrently, one thread
 498         // will see global.manager null and call LogManager.getLogManager(),
 499         // but the other thread could come in at a time when global.manager
 500         // is already set although ensureLogManagerInitialized is not finished
 501         // yet...
 502         // Calling LogManager.getLogManager() unconditionally will fix that.
 503 
 504         LogManager.getLogManager();
 505 
 506         // Now the global LogManager should be initialized,
 507         // and the global logger should have been added to
 508         // it, unless we were called within the constructor of a LogManager
 509         // subclass installed as LogManager, in which case global.manager
 510         // would still be null, and global will be lazily initialized later on.
 511 
 512         return global;
 513     }
 514 
 515     /**
 516      * The "global" Logger object is provided as a convenience to developers
 517      * who are making casual use of the Logging package.  Developers
 518      * who are making serious use of the logging package (for example
 519      * in products) should create and use their own Logger objects,
 520      * with appropriate names, so that logging can be controlled on a
 521      * suitable per-Logger granularity. Developers also need to keep a
 522      * strong reference to their Logger objects to prevent them from
 523      * being garbage collected.
 524      *
 525      * @deprecated Initialization of this field is prone to deadlocks.
 526      * The field must be initialized by the Logger class initialization
 527      * which may cause deadlocks with the LogManager class initialization.
 528      * In such cases two class initialization wait for each other to complete.
 529      * The preferred way to get the global logger object is via the call
 530      * {@code Logger.getGlobal()}.
 531      * For compatibility with old JDK versions where the
 532      * {@code Logger.getGlobal()} is not available use the call
 533      * {@code Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)}
 534      * or {@code Logger.getLogger("global")}.
 535      */
 536     @Deprecated
 537     public static final Logger global = new Logger(GLOBAL_LOGGER_NAME);
 538 
 539     /**
 540      * Protected method to construct a logger for a named subsystem.
 541      * <p>
 542      * The logger will be initially configured with a null Level
 543      * and with useParentHandlers set to true.
 544      *
 545      * @param   name    A name for the logger.  This should
 546      *                          be a dot-separated name and should normally
 547      *                          be based on the package name or class name
 548      *                          of the subsystem, such as java.net
 549      *                          or javax.swing.  It may be null for anonymous Loggers.
 550      * @param   resourceBundleName  name of ResourceBundle to be used for localizing
 551      *                          messages for this logger.  May be null if none
 552      *                          of the messages require localization.
 553      * @throws MissingResourceException if the resourceBundleName is non-null and
 554      *             no corresponding resource can be found.
 555      */
 556     protected Logger(String name, String resourceBundleName) {
 557         this(name, resourceBundleName, null, LogManager.getLogManager(), false);
 558     }
 559 
 560     Logger(String name, String resourceBundleName, Module caller,
 561            LogManager manager, boolean isSystemLogger) {
 562         this.manager = manager;
 563         this.isSystemLogger = isSystemLogger;
 564         this.config = new ConfigurationData();
 565         this.name = name;
 566         setupResourceInfo(resourceBundleName, caller);
 567     }
 568 
 569     // Called by LogManager when a system logger is created
 570     // after a user logger of the same name.
 571     // Ensure that both loggers will share the same
 572     // configuration.
 573     final void mergeWithSystemLogger(Logger system) {
 574         // sanity checks
 575         if (!system.isSystemLogger
 576                 || anonymous
 577                 || name == null
 578                 || !name.equals(system.name)) {
 579             // should never come here
 580             throw new InternalError("invalid logger merge");
 581         }
 582         checkPermission();
 583         final ConfigurationData cfg = config;
 584         if (cfg != system.config) {
 585             config = cfg.merge(system);
 586         }
 587     }
 588 
 589     private void setCallerModuleRef(Module callerModule) {
 590         if (callerModule != null) {
 591             this.callerModuleRef = new WeakReference<>(callerModule);
 592         }
 593     }
 594 
 595     private Module getCallerModule() {
 596         return (callerModuleRef != null)
 597                 ? callerModuleRef.get()
 598                 : null;
 599     }
 600 
 601     // This constructor is used only to create the global Logger.
 602     // It is needed to break a cyclic dependence between the LogManager
 603     // and Logger static initializers causing deadlocks.
 604     private Logger(String name) {
 605         // The manager field is not initialized here.
 606         this.name = name;
 607         this.isSystemLogger = true;
 608         config = new ConfigurationData();
 609     }
 610 
 611     // It is called from LoggerContext.addLocalLogger() when the logger
 612     // is actually added to a LogManager.
 613     void setLogManager(LogManager manager) {
 614         this.manager = manager;
 615     }
 616 
 617     private void checkPermission() throws SecurityException {
 618         if (!anonymous) {
 619             if (manager == null) {
 620                 // Complete initialization of the global Logger.
 621                 manager = LogManager.getLogManager();
 622             }
 623             manager.checkPermission();
 624         }
 625     }
 626 
 627     // Until all JDK code converted to call sun.util.logging.PlatformLogger
 628     // (see 7054233), we need to determine if Logger.getLogger is to add
 629     // a system logger or user logger.
 630     //
 631     // As an interim solution, if the immediate caller whose caller loader is
 632     // null, we assume it's a system logger and add it to the system context.
 633     // These system loggers only set the resource bundle to the given
 634     // resource bundle name (rather than the default system resource bundle).
 635     private static class SystemLoggerHelper {
 636         static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck");
 637         private static boolean getBooleanProperty(final String key) {
 638             @SuppressWarnings("removal")
 639             String s = AccessController.doPrivileged(new PrivilegedAction<String>() {
 640                 @Override
 641                 public String run() {
 642                     return System.getProperty(key);
 643                 }
 644             });
 645             return Boolean.parseBoolean(s);
 646         }
 647     }
 648 
 649     private static Logger demandLogger(String name, String resourceBundleName, Class<?> caller) {
 650         LogManager manager = LogManager.getLogManager();
 651         if (!SystemLoggerHelper.disableCallerCheck) {
 652             if (isSystem(caller.getModule())) {
 653                 return manager.demandSystemLogger(name, resourceBundleName, caller);
 654             }
 655         }
 656         return manager.demandLogger(name, resourceBundleName, caller);
 657         // ends up calling new Logger(name, resourceBundleName, caller)
 658         // iff the logger doesn't exist already
 659     }
 660 
 661     /**
 662      * Find or create a logger for a named subsystem.  If a logger has
 663      * already been created with the given name it is returned.  Otherwise
 664      * a new logger is created.
 665      * <p>
 666      * If a new logger is created its log level will be configured
 667      * based on the LogManager configuration and it will be configured
 668      * to also send logging output to its parent's Handlers.  It will
 669      * be registered in the LogManager global namespace.
 670      * <p>
 671      * Note: The LogManager may only retain a weak reference to the newly
 672      * created Logger. It is important to understand that a previously
 673      * created Logger with the given name may be garbage collected at any
 674      * time if there is no strong reference to the Logger. In particular,
 675      * this means that two back-to-back calls like
 676      * {@code getLogger("MyLogger").log(...)} may use different Logger
 677      * objects named "MyLogger" if there is no strong reference to the
 678      * Logger named "MyLogger" elsewhere in the program.
 679      *
 680      * @param   name            A name for the logger.  This should
 681      *                          be a dot-separated name and should normally
 682      *                          be based on the package name or class name
 683      *                          of the subsystem, such as java.net
 684      *                          or javax.swing
 685      * @return a suitable Logger
 686      * @throws NullPointerException if the name is null.
 687      */
 688 
 689     // Synchronization is not required here. All synchronization for
 690     // adding a new Logger object is handled by LogManager.addLogger().
 691     @CallerSensitive
 692     public static Logger getLogger(String name) {
 693         // This method is intentionally not a wrapper around a call
 694         // to getLogger(name, resourceBundleName). If it were then
 695         // this sequence:
 696         //
 697         //     getLogger("Foo", "resourceBundleForFoo");
 698         //     getLogger("Foo");
 699         //
 700         // would throw an IllegalArgumentException in the second call
 701         // because the wrapper would result in an attempt to replace
 702         // the existing "resourceBundleForFoo" with null.
 703         return Logger.getLogger(name, Reflection.getCallerClass());
 704     }
 705 
 706     /**
 707      * Find or create a logger for a named subsystem on behalf
 708      * of the given caller.
 709      *
 710      * This method is called by {@link #getLogger(java.lang.String)} after
 711      * it has obtained a reference to its caller's class.
 712      *
 713      * @param   name            A name for the logger.
 714      * @param   callerClass     The class that called {@link
 715      *                          #getLogger(java.lang.String)}.
 716      * @return a suitable Logger for {@code callerClass}.
 717      */
 718     @CallerSensitiveAdapter
 719     private static Logger getLogger(String name, Class<?> callerClass) {
 720         return demandLogger(name, null, callerClass);
 721     }
 722 
 723     /**
 724      * Find or create a logger for a named subsystem.  If a logger has
 725      * already been created with the given name it is returned.  Otherwise
 726      * a new logger is created.
 727      *
 728      * <p>
 729      * If a new logger is created its log level will be configured
 730      * based on the LogManager and it will be configured to also send logging
 731      * output to its parent's Handlers.  It will be registered in
 732      * the LogManager global namespace.
 733      * <p>
 734      * Note: The LogManager may only retain a weak reference to the newly
 735      * created Logger. It is important to understand that a previously
 736      * created Logger with the given name may be garbage collected at any
 737      * time if there is no strong reference to the Logger. In particular,
 738      * this means that two back-to-back calls like
 739      * {@code getLogger("MyLogger", ...).log(...)} may use different Logger
 740      * objects named "MyLogger" if there is no strong reference to the
 741      * Logger named "MyLogger" elsewhere in the program.
 742      * <p>
 743      * If the named Logger already exists and does not yet have a
 744      * localization resource bundle then the given resource bundle
 745      * name is used. If the named Logger already exists and has
 746      * a different resource bundle name then an IllegalArgumentException
 747      * is thrown.
 748      *
 749      * @param   name    A name for the logger.  This should
 750      *                          be a dot-separated name and should normally
 751      *                          be based on the package name or class name
 752      *                          of the subsystem, such as java.net
 753      *                          or javax.swing
 754      * @param   resourceBundleName  name of ResourceBundle to be used for localizing
 755      *                          messages for this logger. May be {@code null}
 756      *                          if none of the messages require localization.
 757      * @return a suitable Logger
 758      * @throws MissingResourceException if the resourceBundleName is non-null and
 759      *             no corresponding resource can be found.
 760      * @throws IllegalArgumentException if the Logger already exists and uses
 761      *             a different resource bundle name; or if
 762      *             {@code resourceBundleName} is {@code null} but the named
 763      *             logger has a resource bundle set.
 764      * @throws NullPointerException if the name is null.
 765      */
 766 
 767     // Synchronization is not required here. All synchronization for
 768     // adding a new Logger object is handled by LogManager.addLogger().
 769     @CallerSensitive
 770     public static Logger getLogger(String name, String resourceBundleName) {
 771         return Logger.getLogger(name, resourceBundleName, Reflection.getCallerClass());
 772     }
 773 
 774     /**
 775      * Find or create a logger for a named subsystem on behalf
 776      * of the given caller.
 777      *
 778      * This method is called by {@link
 779      * #getLogger(java.lang.String, java.lang.String)} after
 780      * it has obtained a reference to its caller's class.
 781      *
 782      * @param   name            A name for the logger.
 783      * @param   resourceBundleName  name of ResourceBundle to be used for localizing
 784      *                          messages for this logger. May be {@code null}
 785      *                          if none of the messages require localization.
 786      * @param   callerClass     The class that called {@link
 787      *                          #getLogger(java.lang.String, java.lang.String)}.
 788      *                          This class will also be used for locating the
 789      *                          resource bundle if {@code resourceBundleName} is
 790      *                          not {@code null}.
 791      * @return a suitable Logger for {@code callerClass}.
 792      */
 793     @CallerSensitiveAdapter
 794     private static Logger getLogger(String name, String resourceBundleName,
 795                                     Class<?> callerClass) {
 796         Logger result = demandLogger(name, resourceBundleName, callerClass);
 797 
 798         // MissingResourceException or IllegalArgumentException can be
 799         // thrown by setupResourceInfo().
 800         // We have to set the callers ClassLoader here in case demandLogger
 801         // above found a previously created Logger.  This can happen, for
 802         // example, if Logger.getLogger(name) is called and subsequently
 803         // Logger.getLogger(name, resourceBundleName) is called.  In this case
 804         // we won't necessarily have the correct classloader saved away, so
 805         // we need to set it here, too.
 806 
 807         result.setupResourceInfo(resourceBundleName, callerClass);
 808         return result;
 809     }
 810 
 811     // package-private
 812     // Add a platform logger to the system context.
 813     // i.e. caller of sun.util.logging.PlatformLogger.getLogger
 814     static Logger getPlatformLogger(String name) {
 815         LogManager manager = LogManager.getLogManager();
 816 
 817         // all loggers in the system context will default to
 818         // the system logger's resource bundle - therefore the caller won't
 819         // be needed and can be null.
 820         Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME, (Module)null);
 821         return result;
 822     }
 823 
 824     /**
 825      * Create an anonymous Logger.  The newly created Logger is not
 826      * registered in the LogManager namespace.  There will be no
 827      * access checks on updates to the logger.
 828      * <p>
 829      * This factory method is primarily intended for use from applets.
 830      * Because the resulting Logger is anonymous it can be kept private
 831      * by the creating class.  This removes the need for normal security
 832      * checks, which in turn allows untrusted applet code to update
 833      * the control state of the Logger.  For example an applet can do
 834      * a setLevel or an addHandler on an anonymous Logger.
 835      * <p>
 836      * Even although the new logger is anonymous, it is configured
 837      * to have the root logger ("") as its parent.  This means that
 838      * by default it inherits its effective level and handlers
 839      * from the root logger. Changing its parent via the
 840      * {@link #setParent(java.util.logging.Logger) setParent} method
 841      * will still require the security permission specified by that method.
 842      *
 843      * @return a newly created private Logger
 844      */
 845     public static Logger getAnonymousLogger() {
 846         return getAnonymousLogger(null);
 847     }
 848 
 849     /**
 850      * Create an anonymous Logger.  The newly created Logger is not
 851      * registered in the LogManager namespace.  There will be no
 852      * access checks on updates to the logger.
 853      * <p>
 854      * This factory method is primarily intended for use from applets.
 855      * Because the resulting Logger is anonymous it can be kept private
 856      * by the creating class.  This removes the need for normal security
 857      * checks, which in turn allows untrusted applet code to update
 858      * the control state of the Logger.  For example an applet can do
 859      * a setLevel or an addHandler on an anonymous Logger.
 860      * <p>
 861      * Even although the new logger is anonymous, it is configured
 862      * to have the root logger ("") as its parent.  This means that
 863      * by default it inherits its effective level and handlers
 864      * from the root logger.  Changing its parent via the
 865      * {@link #setParent(java.util.logging.Logger) setParent} method
 866      * will still require the security permission specified by that method.
 867      *
 868      * @param   resourceBundleName  name of ResourceBundle to be used for localizing
 869      *                          messages for this logger.
 870      *          May be null if none of the messages require localization.
 871      * @return a newly created private Logger
 872      * @throws MissingResourceException if the resourceBundleName is non-null and
 873      *             no corresponding resource can be found.
 874      */
 875 
 876     // Synchronization is not required here. All synchronization for
 877     // adding a new anonymous Logger object is handled by doSetParent().
 878     @CallerSensitive
 879     public static Logger getAnonymousLogger(String resourceBundleName) {
 880         LogManager manager = LogManager.getLogManager();
 881         // cleanup some Loggers that have been GC'ed
 882         manager.drainLoggerRefQueueBounded();
 883         final Class<?> callerClass = Reflection.getCallerClass();
 884         final Module module = callerClass.getModule();
 885         Logger result = new Logger(null, resourceBundleName,
 886                                    module, manager, false);
 887         result.anonymous = true;
 888         Logger root = manager.getLogger("");
 889         result.doSetParent(root);
 890         return result;
 891     }
 892 
 893     /**
 894      * Retrieve the localization resource bundle for this
 895      * logger.
 896      * This method will return a {@code ResourceBundle} that was either
 897      * set by the {@link
 898      * #setResourceBundle(java.util.ResourceBundle) setResourceBundle} method or
 899      * <a href="#ResourceBundleMapping">mapped from the
 900      * the resource bundle name</a> set via the {@link
 901      * Logger#getLogger(java.lang.String, java.lang.String) getLogger} factory
 902      * method for the current default locale.
 903      * <br>Note that if the result is {@code null}, then the Logger will use a resource
 904      * bundle or resource bundle name inherited from its parent.
 905      *
 906      * @return localization bundle (may be {@code null})
 907      */
 908     public ResourceBundle getResourceBundle() {
 909         return findResourceBundle(getResourceBundleName(), true);
 910     }
 911 
 912     /**
 913      * Retrieve the localization resource bundle name for this
 914      * logger.
 915      * This is either the name specified through the {@link
 916      * #getLogger(java.lang.String, java.lang.String) getLogger} factory method,
 917      * or the {@linkplain ResourceBundle#getBaseBundleName() base name} of the
 918      * ResourceBundle set through {@link
 919      * #setResourceBundle(java.util.ResourceBundle) setResourceBundle} method.
 920      * <br>Note that if the result is {@code null}, then the Logger will use a resource
 921      * bundle or resource bundle name inherited from its parent.
 922      *
 923      * @return localization bundle name (may be {@code null})
 924      */
 925     public String getResourceBundleName() {
 926         return loggerBundle.resourceBundleName;
 927     }
 928 
 929     /**
 930      * Set a filter to control output on this Logger.
 931      * <P>
 932      * After passing the initial "level" check, the Logger will
 933      * call this Filter to check if a log record should really
 934      * be published.
 935      *
 936      * @param   newFilter  a filter object (may be null)
 937      * @throws  SecurityException if a security manager exists,
 938      *          this logger is not anonymous, and the caller
 939      *          does not have LoggingPermission("control").
 940      */
 941     public void setFilter(Filter newFilter) throws SecurityException {
 942         checkPermission();
 943         config.setFilter(newFilter);
 944     }
 945 
 946     /**
 947      * Get the current filter for this Logger.
 948      *
 949      * @return  a filter object (may be null)
 950      */
 951     public Filter getFilter() {
 952         return config.filter;
 953     }
 954 
 955     /**
 956      * Log a LogRecord.
 957      * <p>
 958      * All the other logging methods in this class call through
 959      * this method to actually perform any logging.  Subclasses can
 960      * override this single method to capture all log activity.
 961      *
 962      * @param record the LogRecord to be published
 963      */
 964     public void log(LogRecord record) {
 965         if (!isLoggable(record.getLevel())) {
 966             return;
 967         }
 968         Filter theFilter = config.filter;
 969         if (theFilter != null && !theFilter.isLoggable(record)) {
 970             return;
 971         }
 972 
 973         // Post the LogRecord to all our Handlers, and then to
 974         // our parents' handlers, all the way up the tree.
 975 
 976         Logger logger = this;
 977         while (logger != null) {
 978             final Handler[] loggerHandlers = isSystemLogger
 979                 ? logger.accessCheckedHandlers()
 980                 : logger.getHandlers();
 981 
 982             for (Handler handler : loggerHandlers) {
 983                 handler.publish(record);
 984             }
 985 
 986             final boolean useParentHdls = isSystemLogger
 987                 ? logger.config.useParentHandlers
 988                 : logger.getUseParentHandlers();
 989 
 990             if (!useParentHdls) {
 991                 break;
 992             }
 993 
 994             logger = isSystemLogger ? logger.parent : logger.getParent();
 995         }
 996     }
 997 
 998     // private support method for logging.
 999     // We fill in the logger name, resource bundle name, and
1000     // resource bundle and then call "void log(LogRecord)".
1001     private void doLog(LogRecord lr) {
1002         lr.setLoggerName(name);
1003         final LoggerBundle lb = getEffectiveLoggerBundle();
1004         final ResourceBundle  bundle = lb.userBundle;
1005         final String ebname = lb.resourceBundleName;
1006         if (ebname != null && bundle != null) {
1007             lr.setResourceBundleName(ebname);
1008             lr.setResourceBundle(bundle);
1009         }
1010         log(lr);
1011     }
1012 
1013 
1014     //================================================================
1015     // Start of convenience methods WITHOUT className and methodName
1016     //================================================================
1017 
1018     /**
1019      * Log a message, with no arguments.
1020      * <p>
1021      * If the logger is currently enabled for the given message
1022      * level then the given message is forwarded to all the
1023      * registered output Handler objects.
1024      *
1025      * @param   level   One of the message level identifiers, e.g., SEVERE
1026      * @param   msg     The string message (or a key in the message catalog)
1027      */
1028     public void log(Level level, String msg) {
1029         if (!isLoggable(level)) {
1030             return;
1031         }
1032         LogRecord lr = new LogRecord(level, msg);
1033         doLog(lr);
1034     }
1035 
1036     /**
1037      * Log a message, which is only to be constructed if the logging level
1038      * is such that the message will actually be logged.
1039      * <p>
1040      * If the logger is currently enabled for the given message
1041      * level then the message is constructed by invoking the provided
1042      * supplier function and forwarded to all the registered output
1043      * Handler objects.
1044      *
1045      * @param   level   One of the message level identifiers, e.g., SEVERE
1046      * @param   msgSupplier   A function, which when called, produces the
1047      *                        desired log message
1048      * @since 1.8
1049      */
1050     public void log(Level level, Supplier<String> msgSupplier) {
1051         if (!isLoggable(level)) {
1052             return;
1053         }
1054         LogRecord lr = new LogRecord(level, msgSupplier.get());
1055         doLog(lr);
1056     }
1057 
1058     /**
1059      * Log a message, with one object parameter.
1060      * <p>
1061      * If the logger is currently enabled for the given message
1062      * level then a corresponding LogRecord is created and forwarded
1063      * to all the registered output Handler objects.
1064      *
1065      * @param   level   One of the message level identifiers, e.g., SEVERE
1066      * @param   msg     The string message (or a key in the message catalog)
1067      * @param   param1  parameter to the message
1068      */
1069     public void log(Level level, String msg, Object param1) {
1070         if (!isLoggable(level)) {
1071             return;
1072         }
1073         LogRecord lr = new LogRecord(level, msg);
1074         Object params[] = { param1 };
1075         lr.setParameters(params);
1076         doLog(lr);
1077     }
1078 
1079     /**
1080      * Log a message, with an array of object arguments.
1081      * <p>
1082      * If the logger is currently enabled for the given message
1083      * level then a corresponding LogRecord is created and forwarded
1084      * to all the registered output Handler objects.
1085      *
1086      * @param   level   One of the message level identifiers, e.g., SEVERE
1087      * @param   msg     The string message (or a key in the message catalog)
1088      * @param   params  array of parameters to the message
1089      */
1090     public void log(Level level, String msg, Object params[]) {
1091         if (!isLoggable(level)) {
1092             return;
1093         }
1094         LogRecord lr = new LogRecord(level, msg);
1095         lr.setParameters(params);
1096         doLog(lr);
1097     }
1098 
1099     /**
1100      * Log a message, 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      * Note that the thrown argument is stored in the LogRecord thrown
1107      * property, rather than the LogRecord parameters property.  Thus it is
1108      * processed specially by output Formatters and is not treated
1109      * as a formatting parameter to the LogRecord message property.
1110      *
1111      * @param   level   One of the message level identifiers, e.g., SEVERE
1112      * @param   msg     The string message (or a key in the message catalog)
1113      * @param   thrown  Throwable associated with log message.
1114      */
1115     public void log(Level level, String msg, Throwable thrown) {
1116         if (!isLoggable(level)) {
1117             return;
1118         }
1119         LogRecord lr = new LogRecord(level, msg);
1120         lr.setThrown(thrown);
1121         doLog(lr);
1122     }
1123 
1124     /**
1125      * Log a lazily constructed message, with associated Throwable information.
1126      * <p>
1127      * If the logger is currently enabled for the given message level then the
1128      * message is constructed by invoking the provided supplier function. The
1129      * message and the given {@link Throwable} are then stored in a {@link
1130      * LogRecord} which is forwarded to all registered output handlers.
1131      * <p>
1132      * Note that the thrown argument is stored in the LogRecord thrown
1133      * property, rather than the LogRecord parameters property.  Thus it is
1134      * processed specially by output Formatters and is not treated
1135      * as a formatting parameter to the LogRecord message property.
1136      *
1137      * @param   level   One of the message level identifiers, e.g., SEVERE
1138      * @param   thrown  Throwable associated with log message.
1139      * @param   msgSupplier   A function, which when called, produces the
1140      *                        desired log message
1141      * @since   1.8
1142      */
1143     public void log(Level level, Throwable thrown, Supplier<String> msgSupplier) {
1144         if (!isLoggable(level)) {
1145             return;
1146         }
1147         LogRecord lr = new LogRecord(level, msgSupplier.get());
1148         lr.setThrown(thrown);
1149         doLog(lr);
1150     }
1151 
1152     //================================================================
1153     // Start of convenience methods WITH className and methodName
1154     //================================================================
1155 
1156     /**
1157      * Log a message, specifying source class and method,
1158      * with no arguments.
1159      * <p>
1160      * If the logger is currently enabled for the given message
1161      * level then the given message is forwarded to all the
1162      * registered output Handler objects.
1163      *
1164      * @param   level   One of the message level identifiers, e.g., SEVERE
1165      * @param   sourceClass    name of class that issued the logging request
1166      * @param   sourceMethod   name of method that issued the logging request
1167      * @param   msg     The string message (or a key in the message catalog)
1168      */
1169     public void logp(Level level, String sourceClass, String sourceMethod, String msg) {
1170         if (!isLoggable(level)) {
1171             return;
1172         }
1173         LogRecord lr = new LogRecord(level, msg);
1174         lr.setSourceClassName(sourceClass);
1175         lr.setSourceMethodName(sourceMethod);
1176         doLog(lr);
1177     }
1178 
1179     /**
1180      * Log a lazily constructed message, specifying source class and method,
1181      * with no arguments.
1182      * <p>
1183      * If the logger is currently enabled for the given message
1184      * level then the message is constructed by invoking the provided
1185      * supplier function and forwarded to all the registered output
1186      * Handler objects.
1187      *
1188      * @param   level   One of the message level identifiers, e.g., SEVERE
1189      * @param   sourceClass    name of class that issued the logging request
1190      * @param   sourceMethod   name of method that issued the logging request
1191      * @param   msgSupplier   A function, which when called, produces the
1192      *                        desired log message
1193      * @since   1.8
1194      */
1195     public void logp(Level level, String sourceClass, String sourceMethod,
1196                      Supplier<String> msgSupplier) {
1197         if (!isLoggable(level)) {
1198             return;
1199         }
1200         LogRecord lr = new LogRecord(level, msgSupplier.get());
1201         lr.setSourceClassName(sourceClass);
1202         lr.setSourceMethodName(sourceMethod);
1203         doLog(lr);
1204     }
1205 
1206     /**
1207      * Log a message, specifying source class and method,
1208      * with a single object parameter to the log message.
1209      * <p>
1210      * If the logger is currently enabled for the given message
1211      * level then a corresponding LogRecord is created and forwarded
1212      * to all the registered output Handler objects.
1213      *
1214      * @param   level   One of the message level identifiers, e.g., SEVERE
1215      * @param   sourceClass    name of class that issued the logging request
1216      * @param   sourceMethod   name of method that issued the logging request
1217      * @param   msg      The string message (or a key in the message catalog)
1218      * @param   param1    Parameter to the log message.
1219      */
1220     public void logp(Level level, String sourceClass, String sourceMethod,
1221                                                 String msg, Object param1) {
1222         if (!isLoggable(level)) {
1223             return;
1224         }
1225         LogRecord lr = new LogRecord(level, msg);
1226         lr.setSourceClassName(sourceClass);
1227         lr.setSourceMethodName(sourceMethod);
1228         Object params[] = { param1 };
1229         lr.setParameters(params);
1230         doLog(lr);
1231     }
1232 
1233     /**
1234      * Log a message, specifying source class and method,
1235      * with an array of object arguments.
1236      * <p>
1237      * If the logger is currently enabled for the given message
1238      * level then a corresponding LogRecord is created and forwarded
1239      * to all the registered output Handler objects.
1240      *
1241      * @param   level   One of the message level identifiers, e.g., SEVERE
1242      * @param   sourceClass    name of class that issued the logging request
1243      * @param   sourceMethod   name of method that issued the logging request
1244      * @param   msg     The string message (or a key in the message catalog)
1245      * @param   params  Array of parameters to the message
1246      */
1247     public void logp(Level level, String sourceClass, String sourceMethod,
1248                                                 String msg, Object params[]) {
1249         if (!isLoggable(level)) {
1250             return;
1251         }
1252         LogRecord lr = new LogRecord(level, msg);
1253         lr.setSourceClassName(sourceClass);
1254         lr.setSourceMethodName(sourceMethod);
1255         lr.setParameters(params);
1256         doLog(lr);
1257     }
1258 
1259     /**
1260      * Log a message, specifying source class and method,
1261      * with associated Throwable information.
1262      * <p>
1263      * If the logger is currently enabled for the given message
1264      * level then the given arguments are stored in a LogRecord
1265      * which is forwarded to all registered output handlers.
1266      * <p>
1267      * Note that the thrown argument is stored in the LogRecord thrown
1268      * property, rather than the LogRecord parameters property.  Thus it is
1269      * processed specially by output Formatters and is not treated
1270      * as a formatting parameter to the LogRecord message property.
1271      *
1272      * @param   level   One of the message level identifiers, e.g., SEVERE
1273      * @param   sourceClass    name of class that issued the logging request
1274      * @param   sourceMethod   name of method that issued the logging request
1275      * @param   msg     The string message (or a key in the message catalog)
1276      * @param   thrown  Throwable associated with log message.
1277      */
1278     public void logp(Level level, String sourceClass, String sourceMethod,
1279                      String msg, Throwable thrown) {
1280         if (!isLoggable(level)) {
1281             return;
1282         }
1283         LogRecord lr = new LogRecord(level, msg);
1284         lr.setSourceClassName(sourceClass);
1285         lr.setSourceMethodName(sourceMethod);
1286         lr.setThrown(thrown);
1287         doLog(lr);
1288     }
1289 
1290     /**
1291      * Log a lazily constructed message, specifying source class and method,
1292      * with associated Throwable information.
1293      * <p>
1294      * If the logger is currently enabled for the given message level then the
1295      * message is constructed by invoking the provided supplier function. The
1296      * message and the given {@link Throwable} are then stored in a {@link
1297      * LogRecord} which is forwarded to all registered output handlers.
1298      * <p>
1299      * Note that the thrown argument is stored in the LogRecord thrown
1300      * property, rather than the LogRecord parameters property.  Thus it is
1301      * processed specially by output Formatters and is not treated
1302      * as a formatting parameter to the LogRecord message property.
1303      *
1304      * @param   level   One of the message level identifiers, e.g., SEVERE
1305      * @param   sourceClass    name of class that issued the logging request
1306      * @param   sourceMethod   name of method that issued the logging request
1307      * @param   thrown  Throwable associated with log message.
1308      * @param   msgSupplier   A function, which when called, produces the
1309      *                        desired log message
1310      * @since   1.8
1311      */
1312     public void logp(Level level, String sourceClass, String sourceMethod,
1313                      Throwable thrown, Supplier<String> msgSupplier) {
1314         if (!isLoggable(level)) {
1315             return;
1316         }
1317         LogRecord lr = new LogRecord(level, msgSupplier.get());
1318         lr.setSourceClassName(sourceClass);
1319         lr.setSourceMethodName(sourceMethod);
1320         lr.setThrown(thrown);
1321         doLog(lr);
1322     }
1323 
1324 
1325     //=========================================================================
1326     // Start of convenience methods WITH className, methodName and bundle name.
1327     //=========================================================================
1328 
1329     // Private support method for logging for "logrb" methods.
1330     // We fill in the logger name, resource bundle name, and
1331     // resource bundle and then call "void log(LogRecord)".
1332     private void doLog(LogRecord lr, String rbname) {
1333         lr.setLoggerName(name);
1334         if (rbname != null) {
1335             lr.setResourceBundleName(rbname);
1336             lr.setResourceBundle(findResourceBundle(rbname, false));
1337         }
1338         log(lr);
1339     }
1340 
1341     // Private support method for logging for "logrb" methods.
1342     private void doLog(LogRecord lr, ResourceBundle rb) {
1343         lr.setLoggerName(name);
1344         if (rb != null) {
1345             lr.setResourceBundleName(rb.getBaseBundleName());
1346             lr.setResourceBundle(rb);
1347         }
1348         log(lr);
1349     }
1350 
1351     /**
1352      * Log a message, specifying source class, method, and resource bundle name
1353      * with no arguments.
1354      * <p>
1355      * If the logger is currently enabled for the given message
1356      * level then the given message is forwarded to all the
1357      * registered output Handler objects.
1358      * <p>
1359      * The msg string is localized using the named resource bundle.  If the
1360      * resource bundle name is null, or an empty String or invalid
1361      * then the msg string is not localized.
1362      *
1363      * @param   level   One of the message level identifiers, e.g., SEVERE
1364      * @param   sourceClass    name of class that issued the logging request
1365      * @param   sourceMethod   name of method that issued the logging request
1366      * @param   bundleName     name of resource bundle to localize msg,
1367      *                         can be null
1368      * @param   msg     The string message (or a key in the message catalog)
1369      * @deprecated Use {@link #logrb(java.util.logging.Level, java.lang.String,
1370      * java.lang.String, java.util.ResourceBundle, java.lang.String,
1371      * java.lang.Object...)} instead.
1372      */
1373     @Deprecated
1374     public void logrb(Level level, String sourceClass, String sourceMethod,
1375                                 String bundleName, String msg) {
1376         if (!isLoggable(level)) {
1377             return;
1378         }
1379         LogRecord lr = new LogRecord(level, msg);
1380         lr.setSourceClassName(sourceClass);
1381         lr.setSourceMethodName(sourceMethod);
1382         doLog(lr, bundleName);
1383     }
1384 
1385     /**
1386      * Log a message, specifying source class, method, and resource bundle name,
1387      * with a single object parameter to the log message.
1388      * <p>
1389      * If the logger is currently enabled for the given message
1390      * level then a corresponding LogRecord is created and forwarded
1391      * to all the registered output Handler objects.
1392      * <p>
1393      * The msg string is localized using the named resource bundle.  If the
1394      * resource bundle name is null, or an empty String or invalid
1395      * then the msg string is not localized.
1396      *
1397      * @param   level   One of the message level identifiers, e.g., SEVERE
1398      * @param   sourceClass    name of class that issued the logging request
1399      * @param   sourceMethod   name of method that issued the logging request
1400      * @param   bundleName     name of resource bundle to localize msg,
1401      *                         can be null
1402      * @param   msg      The string message (or a key in the message catalog)
1403      * @param   param1    Parameter to the log message.
1404      * @deprecated Use {@link #logrb(java.util.logging.Level, java.lang.String,
1405      *   java.lang.String, java.util.ResourceBundle, java.lang.String,
1406      *   java.lang.Object...)} instead
1407      */
1408     @Deprecated
1409     public void logrb(Level level, String sourceClass, String sourceMethod,
1410                                 String bundleName, String msg, Object param1) {
1411         if (!isLoggable(level)) {
1412             return;
1413         }
1414         LogRecord lr = new LogRecord(level, msg);
1415         lr.setSourceClassName(sourceClass);
1416         lr.setSourceMethodName(sourceMethod);
1417         Object params[] = { param1 };
1418         lr.setParameters(params);
1419         doLog(lr, bundleName);
1420     }
1421 
1422     /**
1423      * Log a message, specifying source class, method, and resource bundle name,
1424      * with an array of object arguments.
1425      * <p>
1426      * If the logger is currently enabled for the given message
1427      * level then a corresponding LogRecord is created and forwarded
1428      * to all the registered output Handler objects.
1429      * <p>
1430      * The msg string is localized using the named resource bundle.  If the
1431      * resource bundle name is null, or an empty String or invalid
1432      * then the msg string is not localized.
1433      *
1434      * @param   level   One of the message level identifiers, e.g., SEVERE
1435      * @param   sourceClass    name of class that issued the logging request
1436      * @param   sourceMethod   name of method that issued the logging request
1437      * @param   bundleName     name of resource bundle to localize msg,
1438      *                         can be null.
1439      * @param   msg     The string message (or a key in the message catalog)
1440      * @param   params  Array of parameters to the message
1441      * @deprecated Use {@link #logrb(java.util.logging.Level, java.lang.String,
1442      *      java.lang.String, java.util.ResourceBundle, java.lang.String,
1443      *      java.lang.Object...)} instead.
1444      */
1445     @Deprecated
1446     public void logrb(Level level, String sourceClass, String sourceMethod,
1447                                 String bundleName, String msg, Object params[]) {
1448         if (!isLoggable(level)) {
1449             return;
1450         }
1451         LogRecord lr = new LogRecord(level, msg);
1452         lr.setSourceClassName(sourceClass);
1453         lr.setSourceMethodName(sourceMethod);
1454         lr.setParameters(params);
1455         doLog(lr, bundleName);
1456     }
1457 
1458     /**
1459      * Log a message, specifying source class, method, and resource bundle,
1460      * with an optional list of message parameters.
1461      * <p>
1462      * If the logger is currently enabled for the given message
1463      * {@code level} then a corresponding {@code LogRecord} is created and
1464      * forwarded to all the registered output {@code Handler} objects.
1465      * <p>
1466      * The {@code msg} string is localized using the given resource bundle.
1467      * If the resource bundle is {@code null}, then the {@code msg} string is not
1468      * localized.
1469      *
1470      * @param   level   One of the message level identifiers, e.g., {@code SEVERE}
1471      * @param   sourceClass    Name of the class that issued the logging request
1472      * @param   sourceMethod   Name of the method that issued the logging request
1473      * @param   bundle         Resource bundle to localize {@code msg},
1474      *                         can be {@code null}.
1475      * @param   msg     The string message (or a key in the message catalog)
1476      * @param   params  Parameters to the message (optional, may be none).
1477      * @since 1.8
1478      */
1479     public void logrb(Level level, String sourceClass, String sourceMethod,
1480                       ResourceBundle bundle, String msg, Object... params) {
1481         if (!isLoggable(level)) {
1482             return;
1483         }
1484         LogRecord lr = new LogRecord(level, msg);
1485         lr.setSourceClassName(sourceClass);
1486         lr.setSourceMethodName(sourceMethod);
1487         if (params != null && params.length != 0) {
1488             lr.setParameters(params);
1489         }
1490         doLog(lr, bundle);
1491     }
1492 
1493     /**
1494      * Log a message, specifying source class, method, and resource bundle,
1495      * with an optional list of message parameters.
1496      * <p>
1497      * If the logger is currently enabled for the given message
1498      * {@code level} then a corresponding {@code LogRecord} is created
1499      * and forwarded to all the registered output {@code Handler} objects.
1500      * <p>
1501      * The {@code msg} string is localized using the given resource bundle.
1502      * If the resource bundle is {@code null}, then the {@code msg} string is not
1503      * localized.
1504      *
1505      * @param   level   One of the message level identifiers, e.g., {@code SEVERE}
1506      * @param   bundle  Resource bundle to localize {@code msg};
1507      *                  can be {@code null}.
1508      * @param   msg     The string message (or a key in the message catalog)
1509      * @param   params  Parameters to the message (optional, may be none).
1510      * @since 9
1511      */
1512     public void logrb(Level level, ResourceBundle bundle, String msg, Object... params) {
1513         if (!isLoggable(level)) {
1514             return;
1515         }
1516         LogRecord lr = new LogRecord(level, msg);
1517         if (params != null && params.length != 0) {
1518             lr.setParameters(params);
1519         }
1520         doLog(lr, bundle);
1521     }
1522 
1523     /**
1524      * Log a message, specifying source class, method, and resource bundle name,
1525      * with associated Throwable information.
1526      * <p>
1527      * If the logger is currently enabled for the given message
1528      * level then the given arguments are stored in a LogRecord
1529      * which is forwarded to all registered output handlers.
1530      * <p>
1531      * The msg string is localized using the named resource bundle.  If the
1532      * resource bundle name is null, or an empty String or invalid
1533      * then the msg string is not localized.
1534      * <p>
1535      * Note that the thrown argument is stored in the LogRecord thrown
1536      * property, rather than the LogRecord parameters property.  Thus it is
1537      * processed specially by output Formatters and is not treated
1538      * as a formatting parameter to the LogRecord message property.
1539      *
1540      * @param   level   One of the message level identifiers, e.g., SEVERE
1541      * @param   sourceClass    name of class that issued the logging request
1542      * @param   sourceMethod   name of method that issued the logging request
1543      * @param   bundleName     name of resource bundle to localize msg,
1544      *                         can be null
1545      * @param   msg     The string message (or a key in the message catalog)
1546      * @param   thrown  Throwable associated with log message.
1547      * @deprecated Use {@link #logrb(java.util.logging.Level, java.lang.String,
1548      *     java.lang.String, java.util.ResourceBundle, java.lang.String,
1549      *     java.lang.Throwable)} instead.
1550      */
1551     @Deprecated
1552     public void logrb(Level level, String sourceClass, String sourceMethod,
1553                                         String bundleName, String msg, Throwable thrown) {
1554         if (!isLoggable(level)) {
1555             return;
1556         }
1557         LogRecord lr = new LogRecord(level, msg);
1558         lr.setSourceClassName(sourceClass);
1559         lr.setSourceMethodName(sourceMethod);
1560         lr.setThrown(thrown);
1561         doLog(lr, bundleName);
1562     }
1563 
1564     /**
1565      * Log a message, specifying source class, method, and resource bundle,
1566      * with associated Throwable information.
1567      * <p>
1568      * If the logger is currently enabled for the given message
1569      * {@code level} then the given arguments are stored in a {@code LogRecord}
1570      * which is forwarded to all registered output handlers.
1571      * <p>
1572      * The {@code msg} string is localized using the given resource bundle.
1573      * If the resource bundle is {@code null}, then the {@code msg} string is not
1574      * localized.
1575      * <p>
1576      * Note that the {@code thrown} argument is stored in the {@code LogRecord}
1577      * {@code thrown} property, rather than the {@code LogRecord}
1578      * {@code parameters} property.  Thus it is
1579      * processed specially by output {@code Formatter} objects and is not treated
1580      * as a formatting parameter to the {@code LogRecord} {@code message} property.
1581      *
1582      * @param   level   One of the message level identifiers, e.g., {@code SEVERE}
1583      * @param   sourceClass    Name of the class that issued the logging request
1584      * @param   sourceMethod   Name of the method that issued the logging request
1585      * @param   bundle         Resource bundle to localize {@code msg},
1586      *                         can be {@code null}
1587      * @param   msg     The string message (or a key in the message catalog)
1588      * @param   thrown  Throwable associated with the log message.
1589      * @since 1.8
1590      */
1591     public void logrb(Level level, String sourceClass, String sourceMethod,
1592                       ResourceBundle bundle, String msg, Throwable thrown) {
1593         if (!isLoggable(level)) {
1594             return;
1595         }
1596         LogRecord lr = new LogRecord(level, msg);
1597         lr.setSourceClassName(sourceClass);
1598         lr.setSourceMethodName(sourceMethod);
1599         lr.setThrown(thrown);
1600         doLog(lr, bundle);
1601     }
1602 
1603     /**
1604      * Log a message, specifying source class, method, and resource bundle,
1605      * with associated Throwable information.
1606      * <p>
1607      * If the logger is currently enabled for the given message
1608      * {@code level} then the given arguments are stored in a {@code LogRecord}
1609      * which is forwarded to all registered output handlers.
1610      * <p>
1611      * The {@code msg} string is localized using the given resource bundle.
1612      * If the resource bundle is {@code null}, then the {@code msg} string is not
1613      * localized.
1614      * <p>
1615      * Note that the {@code thrown} argument is stored in the {@code LogRecord}
1616      * {@code thrown} property, rather than the {@code LogRecord}
1617      * {@code parameters} property.  Thus it is
1618      * processed specially by output {@code Formatter} objects and is not treated
1619      * as a formatting parameter to the {@code LogRecord} {@code message}
1620      * property.
1621      *
1622      * @param   level   One of the message level identifiers, e.g., {@code SEVERE}
1623      * @param   bundle  Resource bundle to localize {@code msg};
1624      *                  can be {@code null}.
1625      * @param   msg     The string message (or a key in the message catalog)
1626      * @param   thrown  Throwable associated with the log message.
1627      * @since 9
1628      */
1629     public void logrb(Level level, ResourceBundle bundle, String msg,
1630             Throwable thrown) {
1631         if (!isLoggable(level)) {
1632             return;
1633         }
1634         LogRecord lr = new LogRecord(level, msg);
1635         lr.setThrown(thrown);
1636         doLog(lr, bundle);
1637     }
1638 
1639     //======================================================================
1640     // Start of convenience methods for logging method entries and returns.
1641     //======================================================================
1642 
1643     /**
1644      * Log a method entry.
1645      * <p>
1646      * This is a convenience method that can be used to log entry
1647      * to a method.  A LogRecord with message "ENTRY", log level
1648      * FINER, and the given sourceMethod and sourceClass is logged.
1649      *
1650      * @param   sourceClass    name of class that issued the logging request
1651      * @param   sourceMethod   name of method that is being entered
1652      */
1653     public void entering(String sourceClass, String sourceMethod) {
1654         logp(Level.FINER, sourceClass, sourceMethod, "ENTRY");
1655     }
1656 
1657     /**
1658      * Log a method entry, with one parameter.
1659      * <p>
1660      * This is a convenience method that can be used to log entry
1661      * to a method.  A LogRecord with message "ENTRY {0}", log level
1662      * FINER, and the given sourceMethod, sourceClass, and parameter
1663      * is logged.
1664      *
1665      * @param   sourceClass    name of class that issued the logging request
1666      * @param   sourceMethod   name of method that is being entered
1667      * @param   param1         parameter to the method being entered
1668      */
1669     public void entering(String sourceClass, String sourceMethod, Object param1) {
1670         logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", param1);
1671     }
1672 
1673     /**
1674      * Log a method entry, with an array of parameters.
1675      * <p>
1676      * This is a convenience method that can be used to log entry
1677      * to a method.  A LogRecord with message "ENTRY" (followed by a
1678      * format {N} indicator for each entry in the parameter array),
1679      * log level FINER, and the given sourceMethod, sourceClass, and
1680      * parameters is logged.
1681      *
1682      * @param   sourceClass    name of class that issued the logging request
1683      * @param   sourceMethod   name of method that is being entered
1684      * @param   params         array of parameters to the method being entered
1685      */
1686     public void entering(String sourceClass, String sourceMethod, Object params[]) {
1687         String msg = "ENTRY";
1688         if (params == null ) {
1689            logp(Level.FINER, sourceClass, sourceMethod, msg);
1690            return;
1691         }
1692         if (!isLoggable(Level.FINER)) return;
1693         if (params.length > 0) {
1694             final StringBuilder b = new StringBuilder(msg);
1695             for (int i = 0; i < params.length; i++) {
1696                 b.append(' ').append('{').append(i).append('}');
1697             }
1698             msg = b.toString();
1699         }
1700         logp(Level.FINER, sourceClass, sourceMethod, msg, params);
1701     }
1702 
1703     /**
1704      * Log a method return.
1705      * <p>
1706      * This is a convenience method that can be used to log returning
1707      * from a method.  A LogRecord with message "RETURN", log level
1708      * FINER, and the given sourceMethod and sourceClass is logged.
1709      *
1710      * @param   sourceClass    name of class that issued the logging request
1711      * @param   sourceMethod   name of the method
1712      */
1713     public void exiting(String sourceClass, String sourceMethod) {
1714         logp(Level.FINER, sourceClass, sourceMethod, "RETURN");
1715     }
1716 
1717 
1718     /**
1719      * Log a method return, with result object.
1720      * <p>
1721      * This is a convenience method that can be used to log returning
1722      * from a method.  A LogRecord with message "RETURN {0}", log level
1723      * FINER, and the gives sourceMethod, sourceClass, and result
1724      * object is logged.
1725      *
1726      * @param   sourceClass    name of class that issued the logging request
1727      * @param   sourceMethod   name of the method
1728      * @param   result  Object that is being returned
1729      */
1730     public void exiting(String sourceClass, String sourceMethod, Object result) {
1731         logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result);
1732     }
1733 
1734     /**
1735      * Log throwing an exception.
1736      * <p>
1737      * This is a convenience method to log that a method is
1738      * terminating by throwing an exception.  The logging is done
1739      * using the FINER level.
1740      * <p>
1741      * If the logger is currently enabled for the given message
1742      * level then the given arguments are stored in a LogRecord
1743      * which is forwarded to all registered output handlers.  The
1744      * LogRecord's message is set to "THROW".
1745      * <p>
1746      * Note that the thrown argument is stored in the LogRecord thrown
1747      * property, rather than the LogRecord parameters property.  Thus it is
1748      * processed specially by output Formatters and is not treated
1749      * as a formatting parameter to the LogRecord message property.
1750      *
1751      * @param   sourceClass    name of class that issued the logging request
1752      * @param   sourceMethod  name of the method.
1753      * @param   thrown  The Throwable that is being thrown.
1754      */
1755     public void throwing(String sourceClass, String sourceMethod, Throwable thrown) {
1756         if (!isLoggable(Level.FINER)) {
1757             return;
1758         }
1759         LogRecord lr = new LogRecord(Level.FINER, "THROW");
1760         lr.setSourceClassName(sourceClass);
1761         lr.setSourceMethodName(sourceMethod);
1762         lr.setThrown(thrown);
1763         doLog(lr);
1764     }
1765 
1766     //=======================================================================
1767     // Start of simple convenience methods using level names as method names
1768     //=======================================================================
1769 
1770     /**
1771      * Log a SEVERE message.
1772      * <p>
1773      * If the logger is currently enabled for the SEVERE message
1774      * level then the given message is forwarded to all the
1775      * registered output Handler objects.
1776      *
1777      * @param   msg     The string message (or a key in the message catalog)
1778      */
1779     public void severe(String msg) {
1780         log(Level.SEVERE, msg);
1781     }
1782 
1783     /**
1784      * Log a WARNING message.
1785      * <p>
1786      * If the logger is currently enabled for the WARNING message
1787      * level then the given message is forwarded to all the
1788      * registered output Handler objects.
1789      *
1790      * @param   msg     The string message (or a key in the message catalog)
1791      */
1792     public void warning(String msg) {
1793         log(Level.WARNING, msg);
1794     }
1795 
1796     /**
1797      * Log an INFO message.
1798      * <p>
1799      * If the logger is currently enabled for the INFO message
1800      * level then the given message is forwarded to all the
1801      * registered output Handler objects.
1802      *
1803      * @param   msg     The string message (or a key in the message catalog)
1804      */
1805     public void info(String msg) {
1806         log(Level.INFO, msg);
1807     }
1808 
1809     /**
1810      * Log a CONFIG message.
1811      * <p>
1812      * If the logger is currently enabled for the CONFIG message
1813      * level then the given message is forwarded to all the
1814      * registered output Handler objects.
1815      *
1816      * @param   msg     The string message (or a key in the message catalog)
1817      */
1818     public void config(String msg) {
1819         log(Level.CONFIG, msg);
1820     }
1821 
1822     /**
1823      * Log a FINE message.
1824      * <p>
1825      * If the logger is currently enabled for the FINE message
1826      * level then the given message is forwarded to all the
1827      * registered output Handler objects.
1828      *
1829      * @param   msg     The string message (or a key in the message catalog)
1830      */
1831     public void fine(String msg) {
1832         log(Level.FINE, msg);
1833     }
1834 
1835     /**
1836      * Log a FINER message.
1837      * <p>
1838      * If the logger is currently enabled for the FINER message
1839      * level then the given message is forwarded to all the
1840      * registered output Handler objects.
1841      *
1842      * @param   msg     The string message (or a key in the message catalog)
1843      */
1844     public void finer(String msg) {
1845         log(Level.FINER, msg);
1846     }
1847 
1848     /**
1849      * Log a FINEST message.
1850      * <p>
1851      * If the logger is currently enabled for the FINEST message
1852      * level then the given message is forwarded to all the
1853      * registered output Handler objects.
1854      *
1855      * @param   msg     The string message (or a key in the message catalog)
1856      */
1857     public void finest(String msg) {
1858         log(Level.FINEST, msg);
1859     }
1860 
1861     //=======================================================================
1862     // Start of simple convenience methods using level names as method names
1863     // and use Supplier<String>
1864     //=======================================================================
1865 
1866     /**
1867      * Log a SEVERE message, which is only to be constructed if the logging
1868      * level is such that the message will actually be logged.
1869      * <p>
1870      * If the logger is currently enabled for the SEVERE message
1871      * level then the message is constructed by invoking the provided
1872      * supplier function and forwarded to all the registered output
1873      * Handler objects.
1874      *
1875      * @param   msgSupplier   A function, which when called, produces the
1876      *                        desired log message
1877      * @since   1.8
1878      */
1879     public void severe(Supplier<String> msgSupplier) {
1880         log(Level.SEVERE, msgSupplier);
1881     }
1882 
1883     /**
1884      * Log a WARNING message, which is only to be constructed if the logging
1885      * level is such that the message will actually be logged.
1886      * <p>
1887      * If the logger is currently enabled for the WARNING message
1888      * level then the message is constructed by invoking the provided
1889      * supplier function and forwarded to all the registered output
1890      * Handler objects.
1891      *
1892      * @param   msgSupplier   A function, which when called, produces the
1893      *                        desired log message
1894      * @since   1.8
1895      */
1896     public void warning(Supplier<String> msgSupplier) {
1897         log(Level.WARNING, msgSupplier);
1898     }
1899 
1900     /**
1901      * Log a INFO message, which is only to be constructed if the logging
1902      * level is such that the message will actually be logged.
1903      * <p>
1904      * If the logger is currently enabled for the INFO message
1905      * level then the message is constructed by invoking the provided
1906      * supplier function and forwarded to all the registered output
1907      * Handler objects.
1908      *
1909      * @param   msgSupplier   A function, which when called, produces the
1910      *                        desired log message
1911      * @since   1.8
1912      */
1913     public void info(Supplier<String> msgSupplier) {
1914         log(Level.INFO, msgSupplier);
1915     }
1916 
1917     /**
1918      * Log a CONFIG message, which is only to be constructed if the logging
1919      * level is such that the message will actually be logged.
1920      * <p>
1921      * If the logger is currently enabled for the CONFIG message
1922      * level then the message is constructed by invoking the provided
1923      * supplier function and forwarded to all the registered output
1924      * Handler objects.
1925      *
1926      * @param   msgSupplier   A function, which when called, produces the
1927      *                        desired log message
1928      * @since   1.8
1929      */
1930     public void config(Supplier<String> msgSupplier) {
1931         log(Level.CONFIG, msgSupplier);
1932     }
1933 
1934     /**
1935      * Log a FINE message, which is only to be constructed if the logging
1936      * level is such that the message will actually be logged.
1937      * <p>
1938      * If the logger is currently enabled for the FINE message
1939      * level then the message is constructed by invoking the provided
1940      * supplier function and forwarded to all the registered output
1941      * Handler objects.
1942      *
1943      * @param   msgSupplier   A function, which when called, produces the
1944      *                        desired log message
1945      * @since   1.8
1946      */
1947     public void fine(Supplier<String> msgSupplier) {
1948         log(Level.FINE, msgSupplier);
1949     }
1950 
1951     /**
1952      * Log a FINER message, which is only to be constructed if the logging
1953      * level is such that the message will actually be logged.
1954      * <p>
1955      * If the logger is currently enabled for the FINER message
1956      * level then the message is constructed by invoking the provided
1957      * supplier function and forwarded to all the registered output
1958      * Handler objects.
1959      *
1960      * @param   msgSupplier   A function, which when called, produces the
1961      *                        desired log message
1962      * @since   1.8
1963      */
1964     public void finer(Supplier<String> msgSupplier) {
1965         log(Level.FINER, msgSupplier);
1966     }
1967 
1968     /**
1969      * Log a FINEST message, which is only to be constructed if the logging
1970      * level is such that the message will actually be logged.
1971      * <p>
1972      * If the logger is currently enabled for the FINEST message
1973      * level then the message is constructed by invoking the provided
1974      * supplier function and forwarded to all the registered output
1975      * Handler objects.
1976      *
1977      * @param   msgSupplier   A function, which when called, produces the
1978      *                        desired log message
1979      * @since   1.8
1980      */
1981     public void finest(Supplier<String> msgSupplier) {
1982         log(Level.FINEST, msgSupplier);
1983     }
1984 
1985     //================================================================
1986     // End of convenience methods
1987     //================================================================
1988 
1989     /**
1990      * Set the log level specifying which message levels will be
1991      * logged by this logger.  Message levels lower than this
1992      * value will be discarded.  The level value Level.OFF
1993      * can be used to turn off logging.
1994      * <p>
1995      * If the new level is null, it means that this node should
1996      * inherit its level from its nearest ancestor with a specific
1997      * (non-null) level value.
1998      *
1999      * @param newLevel   the new value for the log level (may be null)
2000      * @throws  SecurityException if a security manager exists,
2001      *          this logger is not anonymous, and the caller
2002      *          does not have LoggingPermission("control").
2003      */
2004     public void setLevel(Level newLevel) throws SecurityException {
2005         checkPermission();
2006         synchronized (treeLock) {
2007             config.setLevelObject(newLevel);
2008             updateEffectiveLevel();
2009         }
2010     }
2011 
2012     final boolean isLevelInitialized() {
2013         return config.levelObject != null;
2014     }
2015 
2016     /**
2017      * Get the log Level that has been specified for this Logger.
2018      * The result may be null, which means that this logger's
2019      * effective level will be inherited from its parent.
2020      *
2021      * @return  this Logger's level
2022      */
2023     public Level getLevel() {
2024         return config.levelObject;
2025     }
2026 
2027     /**
2028      * Check if a message of the given level would actually be logged
2029      * by this logger.  This check is based on the Loggers effective level,
2030      * which may be inherited from its parent.
2031      *
2032      * @param   level   a message logging level
2033      * @return  true if the given message level is currently being logged.
2034      */
2035     public boolean isLoggable(Level level) {
2036         int levelValue = config.levelValue;
2037         if (level.intValue() < levelValue || levelValue == offValue) {
2038             return false;
2039         }
2040         return true;
2041     }
2042 
2043     /**
2044      * Get the name for this logger.
2045      * @return logger name.  Will be null for anonymous Loggers.
2046      */
2047     public String getName() {
2048         return name;
2049     }
2050 
2051     /**
2052      * Add a log Handler to receive logging messages.
2053      * <p>
2054      * By default, Loggers also send their output to their parent logger.
2055      * Typically the root Logger is configured with a set of Handlers
2056      * that essentially act as default handlers for all loggers.
2057      *
2058      * @param   handler a logging Handler
2059      * @throws  SecurityException if a security manager exists,
2060      *          this logger is not anonymous, and the caller
2061      *          does not have LoggingPermission("control").
2062      */
2063     public void addHandler(Handler handler) throws SecurityException {
2064         Objects.requireNonNull(handler);
2065         checkPermission();
2066         config.addHandler(handler);
2067     }
2068 
2069     /**
2070      * Remove a log Handler.
2071      * <P>
2072      * Returns silently if the given Handler is not found or is null
2073      *
2074      * @param   handler a logging Handler
2075      * @throws  SecurityException if a security manager exists,
2076      *          this logger is not anonymous, and the caller
2077      *          does not have LoggingPermission("control").
2078      */
2079     public void removeHandler(Handler handler) throws SecurityException {
2080         checkPermission();
2081         if (handler == null) {
2082             return;
2083         }
2084         config.removeHandler(handler);
2085     }
2086 
2087     /**
2088      * Get the Handlers associated with this logger.
2089      *
2090      * @return  an array of all registered Handlers
2091      */
2092     public Handler[] getHandlers() {
2093         return accessCheckedHandlers();
2094     }
2095 
2096     // This method should ideally be marked final - but unfortunately
2097     // it needs to be overridden by LogManager.RootLogger
2098     Handler[] accessCheckedHandlers() {
2099         return config.handlers.toArray(emptyHandlers);
2100     }
2101 
2102     /**
2103      * Specify whether or not this logger should send its output
2104      * to its parent Logger.  This means that any LogRecords will
2105      * also be written to the parent's Handlers, and potentially
2106      * to its parent, recursively up the namespace.
2107      *
2108      * @param useParentHandlers   true if output is to be sent to the
2109      *          logger's parent.
2110      * @throws  SecurityException if a security manager exists,
2111      *          this logger is not anonymous, and the caller
2112      *          does not have LoggingPermission("control").
2113      */
2114     public void setUseParentHandlers(boolean useParentHandlers) {
2115         checkPermission();
2116         config.setUseParentHandlers(useParentHandlers);
2117     }
2118 
2119     /**
2120      * Discover whether or not this logger is sending its output
2121      * to its parent logger.
2122      *
2123      * @return  true if output is to be sent to the logger's parent
2124      */
2125     public boolean getUseParentHandlers() {
2126         return config.useParentHandlers;
2127     }
2128 
2129     private ResourceBundle catalog() {
2130         WeakReference<ResourceBundle> ref = catalogRef;
2131         return ref == null ? null : ref.get();
2132     }
2133 
2134     /**
2135      * Private utility method to map a resource bundle name to an
2136      * actual resource bundle, using a simple one-entry cache.
2137      * Returns null for a null name.
2138      * May also return null if we can't find the resource bundle and
2139      * there is no suitable previous cached value.
2140      *
2141      * @param name the ResourceBundle to locate
2142      * @param useCallersModule if true search using the caller's module.
2143      * @return ResourceBundle specified by name or null if not found
2144      */
2145     private synchronized ResourceBundle findResourceBundle(String name,
2146                                                            boolean useCallersModule) {
2147         // When this method is called from logrb, useCallersModule==false, and
2148         // the resource bundle 'name' is the argument provided to logrb.
2149         // It may, or may not be, equal to lb.resourceBundleName.
2150         // Otherwise, useCallersModule==true, and name is the resource bundle
2151         // name that is set (or will be set) in this logger.
2152         //
2153         // When useCallersModule is false, or when the caller's module is
2154         // null, or when the caller's module is an unnamed module, we look
2155         // first in the TCCL (or the System ClassLoader if the TCCL is null)
2156         // to locate the resource bundle.
2157         //
2158         // Otherwise, if useCallersModule is true, and the caller's module is not
2159         // null, and the caller's module is named, we look in the caller's module
2160         // to locate the resource bundle.
2161         //
2162         // Finally, if the caller's module is not null and is unnamed, and
2163         // useCallersModule is true, we look in the caller's module class loader
2164         // (unless we already looked there in step 1).
2165 
2166         // Return a null bundle for a null name.
2167         if (name == null) {
2168             return null;
2169         }
2170 
2171         Locale currentLocale = Locale.getDefault();
2172         final LoggerBundle lb = loggerBundle;
2173         ResourceBundle catalog = catalog();
2174 
2175         // Normally we should hit on our simple one entry cache.
2176         if (lb.userBundle != null &&
2177                 name.equals(lb.resourceBundleName)) {
2178             return lb.userBundle;
2179         } else if (catalog != null && currentLocale.equals(catalogLocale)
2180                     && name.equals(catalogName)) {
2181             return catalog;
2182         }
2183 
2184         // Use the thread's context ClassLoader.  If there isn't one, use the
2185         // {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader}.
2186         ClassLoader cl = Thread.currentThread().getContextClassLoader();
2187         if (cl == null) {
2188             cl = ClassLoader.getSystemClassLoader();
2189         }
2190 
2191         final Module callerModule = getCallerModule();
2192 
2193         // If useCallersModule is false, we are called by logrb, with a name
2194         // that is provided by the user. In that case we will look in the TCCL.
2195         // We also look in the TCCL if callerModule is null or unnamed.
2196         if (!useCallersModule || callerModule == null || !callerModule.isNamed()) {
2197             try {
2198                 Module mod = cl.getUnnamedModule();
2199                 catalog = RbAccess.RB_ACCESS.getBundle(name, currentLocale, mod);
2200                 catalogRef = new WeakReference<>(catalog);
2201                 catalogName = name;
2202                 catalogLocale = currentLocale;
2203                 return catalog;
2204             } catch (MissingResourceException ex) {
2205                 // We can't find the ResourceBundle in the default
2206                 // ClassLoader.  Drop through.
2207                 if (useCallersModule && callerModule != null) {
2208                     try {
2209                         // We are called by an unnamed module: try with the
2210                         // unnamed module class loader:
2211                         PrivilegedAction<ClassLoader> getModuleClassLoader =
2212                                 () -> callerModule.getClassLoader();
2213                         @SuppressWarnings("removal")
2214                         ClassLoader moduleCL =
2215                                 AccessController.doPrivileged(getModuleClassLoader);
2216                         // moduleCL can be null if the logger is created by a class
2217                         // appended to the bootclasspath.
2218                         // If moduleCL is null we would use cl, but we already tried
2219                         // that above (we first looked in the TCCL for unnamed
2220                         // caller modules) - so there no point in trying again: we
2221                         // won't find anything more this second time.
2222                         // In this case just return null.
2223                         if (moduleCL == cl || moduleCL == null) return null;
2224 
2225                         // we already tried the TCCL and found nothing - so try
2226                         // with the module's loader this time.
2227                         catalog = ResourceBundle.getBundle(name, currentLocale,
2228                                                            moduleCL);
2229                         catalogRef = new WeakReference<>(catalog);
2230                         catalogName = name;
2231                         catalogLocale = currentLocale;
2232                         return catalog;
2233                     } catch (MissingResourceException x) {
2234                         return null; // no luck
2235                     }
2236                 } else {
2237                     return null;
2238                 }
2239             }
2240         } else {
2241             // we should have:
2242             //  useCallersModule && callerModule != null && callerModule.isNamed();
2243             // Try with the caller's module
2244             try {
2245                 // Use the caller's module
2246                 catalog = RbAccess.RB_ACCESS.getBundle(name, currentLocale, callerModule);
2247                 catalogRef = new WeakReference<>(catalog);
2248                 catalogName = name;
2249                 catalogLocale = currentLocale;
2250                 return catalog;
2251             } catch (MissingResourceException ex) {
2252                 return null; // no luck
2253             }
2254         }
2255     }
2256 
2257     private void setupResourceInfo(String name, Class<?> caller) {
2258         final Module module = caller == null ? null : caller.getModule();
2259         setupResourceInfo(name, module);
2260     }
2261 
2262     // Private utility method to initialize our one entry
2263     // resource bundle name cache and the callers Module
2264     // Note: for consistency reasons, we are careful to check
2265     // that a suitable ResourceBundle exists before setting the
2266     // resourceBundleName field.
2267     // Synchronized to prevent races in setting the fields.
2268     private synchronized void setupResourceInfo(String name,
2269                                                 Module callerModule) {
2270         final LoggerBundle lb = loggerBundle;
2271         if (lb.resourceBundleName != null) {
2272             // this Logger already has a ResourceBundle
2273 
2274             if (lb.resourceBundleName.equals(name)) {
2275                 // the names match so there is nothing more to do
2276                 return;
2277             }
2278 
2279             // cannot change ResourceBundles once they are set
2280             throw new IllegalArgumentException(
2281                 lb.resourceBundleName + " != " + name);
2282         }
2283 
2284         if (name == null) {
2285             return;
2286         }
2287 
2288         setCallerModuleRef(callerModule);
2289 
2290         if (isSystemLogger && (callerModule != null && !isSystem(callerModule))) {
2291             checkPermission();
2292         }
2293 
2294         if (name.equals(SYSTEM_LOGGER_RB_NAME)) {
2295             loggerBundle = SYSTEM_BUNDLE;
2296         } else {
2297             ResourceBundle bundle = findResourceBundle(name, true);
2298             if (bundle == null) {
2299                 // We've failed to find an expected ResourceBundle.
2300                 // unset the caller's module since we were unable to find the
2301                 // the bundle using it
2302                 this.callerModuleRef = null;
2303                 throw new MissingResourceException("Can't find " + name + " bundle from ",
2304                         name, "");
2305             }
2306 
2307             loggerBundle = LoggerBundle.get(name, null);
2308         }
2309     }
2310 
2311     /**
2312      * Sets a resource bundle on this logger.
2313      * All messages will be logged using the given resource bundle for its
2314      * specific {@linkplain ResourceBundle#getLocale locale}.
2315      * @param bundle The resource bundle that this logger shall use.
2316      * @throws NullPointerException if the given bundle is {@code null}.
2317      * @throws IllegalArgumentException if the given bundle doesn't have a
2318      *         {@linkplain ResourceBundle#getBaseBundleName base name},
2319      *         or if this logger already has a resource bundle set but
2320      *         the given bundle has a different base name.
2321      * @throws SecurityException if a security manager exists,
2322      *         this logger is not anonymous, and the caller
2323      *         does not have LoggingPermission("control").
2324      * @since 1.8
2325      */
2326     public void setResourceBundle(ResourceBundle bundle) {
2327         checkPermission();
2328 
2329         // Will throw NPE if bundle is null.
2330         final String baseName = bundle.getBaseBundleName();
2331 
2332         // bundle must have a name
2333         if (baseName == null || baseName.isEmpty()) {
2334             throw new IllegalArgumentException("resource bundle must have a name");
2335         }
2336 
2337         synchronized (this) {
2338             LoggerBundle lb = loggerBundle;
2339             final boolean canReplaceResourceBundle = lb.resourceBundleName == null
2340                     || lb.resourceBundleName.equals(baseName);
2341 
2342             if (!canReplaceResourceBundle) {
2343                 throw new IllegalArgumentException("can't replace resource bundle");
2344             }
2345 
2346 
2347             loggerBundle = LoggerBundle.get(baseName, bundle);
2348         }
2349     }
2350 
2351     /**
2352      * Return the parent for this Logger.
2353      * <p>
2354      * This method returns the nearest extant parent in the namespace.
2355      * Thus if a Logger is called "a.b.c.d", and a Logger called "a.b"
2356      * has been created but no logger "a.b.c" exists, then a call of
2357      * getParent on the Logger "a.b.c.d" will return the Logger "a.b".
2358      * <p>
2359      * The result will be null if it is called on the root Logger
2360      * in the namespace.
2361      *
2362      * @return nearest existing parent Logger
2363      */
2364     public Logger getParent() {
2365         // Note: this used to be synchronized on treeLock.  However, this only
2366         // provided memory semantics, as there was no guarantee that the caller
2367         // would synchronize on treeLock (in fact, there is no way for external
2368         // callers to so synchronize).  Therefore, we have made parent volatile
2369         // instead.
2370         return parent;
2371     }
2372 
2373     /**
2374      * Set the parent for this Logger.  This method is used by
2375      * the LogManager to update a Logger when the namespace changes.
2376      * <p>
2377      * It should not be called from application code.
2378      *
2379      * @param  parent   the new parent logger
2380      * @throws  SecurityException  if a security manager exists and if
2381      *          the caller does not have LoggingPermission("control").
2382      */
2383     public void setParent(Logger parent) {
2384         if (parent == null) {
2385             throw new NullPointerException();
2386         }
2387 
2388         // check permission for all loggers, including anonymous loggers
2389         if (manager == null) {
2390             manager = LogManager.getLogManager();
2391         }
2392         manager.checkPermission();
2393 
2394         doSetParent(parent);
2395     }
2396 
2397     // Private method to do the work for parenting a child
2398     // Logger onto a parent logger.
2399     private void doSetParent(Logger newParent) {
2400 
2401         // System.err.println("doSetParent \"" + getName() + "\" \""
2402         //                              + newParent.getName() + "\"");
2403 
2404         synchronized (treeLock) {
2405 
2406             // Remove ourself from any previous parent.
2407             LogManager.LoggerWeakRef ref = null;
2408             if (parent != null) {
2409                 // assert parent.kids != null;
2410                 for (Iterator<LogManager.LoggerWeakRef> iter = parent.kids.iterator(); iter.hasNext(); ) {
2411                     ref = iter.next();
2412                     if (ref.refersTo(this)) {
2413                         // ref is used down below to complete the reparenting
2414                         iter.remove();
2415                         break;
2416                     } else {
2417                         ref = null;
2418                     }
2419                 }
2420                 // We have now removed ourself from our parents' kids.
2421             }
2422 
2423             // Set our new parent.
2424             parent = newParent;
2425             if (parent.kids == null) {
2426                 parent.kids = new ArrayList<>(2);
2427             }
2428             if (ref == null) {
2429                 // we didn't have a previous parent
2430                 ref = manager.new LoggerWeakRef(this);
2431             }
2432             ref.setParentRef(new WeakReference<>(parent));
2433             parent.kids.add(ref);
2434 
2435             // As a result of the reparenting, the effective level
2436             // may have changed for us and our children.
2437             updateEffectiveLevel();
2438 
2439         }
2440     }
2441 
2442     // Package-level method.
2443     // Remove the weak reference for the specified child Logger from the
2444     // kid list. We should only be called from LoggerWeakRef.dispose().
2445     final void removeChildLogger(LogManager.LoggerWeakRef child) {
2446         synchronized (treeLock) {
2447             for (Iterator<LogManager.LoggerWeakRef> iter = kids.iterator(); iter.hasNext(); ) {
2448                 LogManager.LoggerWeakRef ref = iter.next();
2449                 if (ref == child) {
2450                     iter.remove();
2451                     return;
2452                 }
2453             }
2454         }
2455     }
2456 
2457     // Recalculate the effective level for this node and
2458     // recursively for our children.
2459 
2460     private void updateEffectiveLevel() {
2461         // assert Thread.holdsLock(treeLock);
2462 
2463         // Figure out our current effective level.
2464         int newLevelValue;
2465         final ConfigurationData cfg = config;
2466         final Level levelObject = cfg.levelObject;
2467         if (levelObject != null) {
2468             newLevelValue = levelObject.intValue();
2469         } else {
2470             if (parent != null) {
2471                 newLevelValue = parent.config.levelValue;
2472             } else {
2473                 // This may happen during initialization.
2474                 newLevelValue = Level.INFO.intValue();
2475             }
2476         }
2477 
2478         // If our effective value hasn't changed, we're done.
2479         if (cfg.levelValue == newLevelValue) {
2480             return;
2481         }
2482 
2483         cfg.setLevelValue(newLevelValue);
2484 
2485         // System.err.println("effective level: \"" + getName() + "\" := " + level);
2486 
2487         // Recursively update the level on each of our kids.
2488         if (kids != null) {
2489             for (LogManager.LoggerWeakRef ref : kids) {
2490                 Logger kid = ref.get();
2491                 if (kid != null) {
2492                     kid.updateEffectiveLevel();
2493                 }
2494             }
2495         }
2496     }
2497 
2498 
2499     // Private method to get the potentially inherited
2500     // resource bundle and resource bundle name for this Logger.
2501     // This method never returns null.
2502     private LoggerBundle getEffectiveLoggerBundle() {
2503         final LoggerBundle lb = loggerBundle;
2504         if (lb.isSystemBundle()) {
2505             return SYSTEM_BUNDLE;
2506         }
2507 
2508         // first take care of this logger
2509         final ResourceBundle b = getResourceBundle();
2510         if (b != null && b == lb.userBundle) {
2511             return lb;
2512         } else if (b != null) {
2513             // either lb.userBundle is null or getResourceBundle() is
2514             // overriden
2515             final String rbName = getResourceBundleName();
2516             return LoggerBundle.get(rbName, b);
2517         }
2518 
2519         // no resource bundle was specified on this logger, look up the
2520         // parent stack.
2521         Logger target = this.parent;
2522         while (target != null) {
2523             final LoggerBundle trb = target.loggerBundle;
2524             if (trb.isSystemBundle()) {
2525                 return SYSTEM_BUNDLE;
2526             }
2527             if (trb.userBundle != null) {
2528                 return trb;
2529             }
2530             final String rbName = isSystemLogger
2531                 // ancestor of a system logger is expected to be a system logger.
2532                 // ignore resource bundle name if it's not.
2533                 ? (target.isSystemLogger ? trb.resourceBundleName : null)
2534                 : target.getResourceBundleName();
2535             if (rbName != null) {
2536                 return LoggerBundle.get(rbName,
2537                         findResourceBundle(rbName, true));
2538             }
2539             target = isSystemLogger ? target.parent : target.getParent();
2540         }
2541         return NO_RESOURCE_BUNDLE;
2542     }
2543 
2544 }