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