1 /* 2 * Copyright (c) 2000, 2016, 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 import java.lang.ref.Reference; 28 import java.lang.ref.ReferenceQueue; 29 import java.lang.ref.WeakReference; 30 import java.lang.reflect.Module; 31 import java.util.ArrayList; 32 import java.util.Collections; 33 import java.util.HashMap; 34 import java.util.List; 35 import java.util.Locale; 36 import java.util.Map; 37 import java.util.Optional; 38 import java.util.ResourceBundle; 39 import java.util.function.Function; 40 import java.util.stream.Stream; 41 42 /** 43 * The Level class defines a set of standard logging levels that 44 * can be used to control logging output. The logging Level objects 45 * are ordered and are specified by ordered integers. Enabling logging 46 * at a given level also enables logging at all higher levels. 47 * <p> 48 * Clients should normally use the predefined Level constants such 49 * as Level.SEVERE. 50 * <p> 51 * The levels in descending order are: 52 * <ul> 53 * <li>SEVERE (highest value) 54 * <li>WARNING 55 * <li>INFO 56 * <li>CONFIG 57 * <li>FINE 58 * <li>FINER 59 * <li>FINEST (lowest value) 60 * </ul> 61 * In addition there is a level OFF that can be used to turn 62 * off logging, and a level ALL that can be used to enable 63 * logging of all messages. 64 * <p> 65 * It is possible for third parties to define additional logging 66 * levels by subclassing Level. In such cases subclasses should 67 * take care to chose unique integer level values and to ensure that 68 * they maintain the Object uniqueness property across serialization 69 * by defining a suitable readResolve method. 70 * 71 * @since 1.4 72 */ 73 74 public class Level implements java.io.Serializable { 75 private static final String defaultBundle = "sun.util.logging.resources.logging"; 76 77 /** 78 * @serial The non-localized name of the level. 79 */ 80 private final String name; 81 82 /** 83 * @serial The integer value of the level. 84 */ 85 private final int value; 86 87 /** 88 * @serial The resource bundle name to be used in localizing the level name. 89 */ 90 private final String resourceBundleName; 91 92 // localized level name 93 private transient String localizedLevelName; 94 private transient Locale cachedLocale; 95 96 /** 97 * OFF is a special level that can be used to turn off logging. 98 * This level is initialized to <CODE>Integer.MAX_VALUE</CODE>. 99 */ 100 public static final Level OFF = new Level("OFF",Integer.MAX_VALUE, defaultBundle); 101 102 /** 103 * SEVERE is a message level indicating a serious failure. 104 * <p> 105 * In general SEVERE messages should describe events that are 106 * of considerable importance and which will prevent normal 107 * program execution. They should be reasonably intelligible 108 * to end users and to system administrators. 109 * This level is initialized to <CODE>1000</CODE>. 110 */ 111 public static final Level SEVERE = new Level("SEVERE",1000, defaultBundle); 112 113 /** 114 * WARNING is a message level indicating a potential problem. 115 * <p> 116 * In general WARNING messages should describe events that will 117 * be of interest to end users or system managers, or which 118 * indicate potential problems. 119 * This level is initialized to <CODE>900</CODE>. 120 */ 121 public static final Level WARNING = new Level("WARNING", 900, defaultBundle); 122 123 /** 124 * INFO is a message level for informational messages. 125 * <p> 126 * Typically INFO messages will be written to the console 127 * or its equivalent. So the INFO level should only be 128 * used for reasonably significant messages that will 129 * make sense to end users and system administrators. 130 * This level is initialized to <CODE>800</CODE>. 131 */ 132 public static final Level INFO = new Level("INFO", 800, defaultBundle); 133 134 /** 135 * CONFIG is a message level for static configuration messages. 136 * <p> 137 * CONFIG messages are intended to provide a variety of static 138 * configuration information, to assist in debugging problems 139 * that may be associated with particular configurations. 140 * For example, CONFIG message might include the CPU type, 141 * the graphics depth, the GUI look-and-feel, etc. 142 * This level is initialized to <CODE>700</CODE>. 143 */ 144 public static final Level CONFIG = new Level("CONFIG", 700, defaultBundle); 145 146 /** 147 * FINE is a message level providing tracing information. 148 * <p> 149 * All of FINE, FINER, and FINEST are intended for relatively 150 * detailed tracing. The exact meaning of the three levels will 151 * vary between subsystems, but in general, FINEST should be used 152 * for the most voluminous detailed output, FINER for somewhat 153 * less detailed output, and FINE for the lowest volume (and 154 * most important) messages. 155 * <p> 156 * In general the FINE level should be used for information 157 * that will be broadly interesting to developers who do not have 158 * a specialized interest in the specific subsystem. 159 * <p> 160 * FINE messages might include things like minor (recoverable) 161 * failures. Issues indicating potential performance problems 162 * are also worth logging as FINE. 163 * This level is initialized to <CODE>500</CODE>. 164 */ 165 public static final Level FINE = new Level("FINE", 500, defaultBundle); 166 167 /** 168 * FINER indicates a fairly detailed tracing message. 169 * By default logging calls for entering, returning, or throwing 170 * an exception are traced at this level. 171 * This level is initialized to <CODE>400</CODE>. 172 */ 173 public static final Level FINER = new Level("FINER", 400, defaultBundle); 174 175 /** 176 * FINEST indicates a highly detailed tracing message. 177 * This level is initialized to <CODE>300</CODE>. 178 */ 179 public static final Level FINEST = new Level("FINEST", 300, defaultBundle); 180 181 /** 182 * ALL indicates that all messages should be logged. 183 * This level is initialized to <CODE>Integer.MIN_VALUE</CODE>. 184 */ 185 public static final Level ALL = new Level("ALL", Integer.MIN_VALUE, defaultBundle); 186 187 /** 188 * Create a named Level with a given integer value. 189 * <p> 190 * Note that this constructor is "protected" to allow subclassing. 191 * In general clients of logging should use one of the constant Level 192 * objects such as SEVERE or FINEST. However, if clients need to 193 * add new logging levels, they may subclass Level and define new 194 * constants. 195 * @param name the name of the Level, for example "SEVERE". 196 * @param value an integer value for the level. 197 * @throws NullPointerException if the name is null 198 */ 199 protected Level(String name, int value) { 200 this(name, value, null); 201 } 202 203 /** 204 * Create a named Level with a given integer value and a 205 * given localization resource name. 206 * 207 * @param name the name of the Level, for example "SEVERE". 208 * @param value an integer value for the level. 209 * @param resourceBundleName name of a resource bundle to use in 210 * localizing the given name. If the resourceBundleName is null 211 * or an empty string, it is ignored. 212 * @throws NullPointerException if the name is null 213 */ 214 protected Level(String name, int value, String resourceBundleName) { 215 this(name, value, resourceBundleName, true); 216 } 217 218 // private constructor to specify whether this instance should be added 219 // to the KnownLevel list from which Level.parse method does its look up 220 private Level(String name, int value, String resourceBundleName, boolean visible) { 221 if (name == null) { 222 throw new NullPointerException(); 223 } 224 this.name = name; 225 this.value = value; 226 this.resourceBundleName = resourceBundleName; 227 this.localizedLevelName = resourceBundleName == null ? name : null; 228 this.cachedLocale = null; 229 if (visible) { 230 KnownLevel.add(this); 231 } 232 } 233 234 /** 235 * Return the level's localization resource bundle name, or 236 * null if no localization bundle is defined. 237 * 238 * @return localization resource bundle name 239 */ 240 public String getResourceBundleName() { 241 return resourceBundleName; 242 } 243 244 /** 245 * Return the non-localized string name of the Level. 246 * 247 * @return non-localized name 248 */ 249 public String getName() { 250 return name; 251 } 252 253 /** 254 * Return the localized string name of the Level, for 255 * the current default locale. 256 * <p> 257 * If no localization information is available, the 258 * non-localized name is returned. 259 * 260 * @return localized name 261 */ 262 public String getLocalizedName() { 263 return getLocalizedLevelName(); 264 } 265 266 // package-private getLevelName() is used by the implementation 267 // instead of getName() to avoid calling the subclass's version 268 final String getLevelName() { 269 return this.name; 270 } 271 272 private String computeLocalizedLevelName(Locale newLocale) { 273 // Resource bundle should be loaded from the defining module 274 // or its defining class loader, if it's unnamed module, 275 // of this Level instance that can be a custom Level subclass; 276 Module module = this.getClass().getModule(); 277 ResourceBundle rb = ResourceBundle.getBundle(resourceBundleName, 278 newLocale, module); 279 280 final String localizedName = rb.getString(name); 281 final boolean isDefaultBundle = defaultBundle.equals(resourceBundleName); 282 if (!isDefaultBundle) return localizedName; 283 284 // This is a trick to determine whether the name has been translated 285 // or not. If it has not been translated, we need to use Locale.ROOT 286 // when calling toUpperCase(). 287 final Locale rbLocale = rb.getLocale(); 288 final Locale locale = 289 Locale.ROOT.equals(rbLocale) 290 || name.equals(localizedName.toUpperCase(Locale.ROOT)) 291 ? Locale.ROOT : rbLocale; 292 293 // ALL CAPS in a resource bundle's message indicates no translation 294 // needed per Oracle translation guideline. To workaround this 295 // in Oracle JDK implementation, convert the localized level name 296 // to uppercase for compatibility reason. 297 return Locale.ROOT.equals(locale) ? name : localizedName.toUpperCase(locale); 298 } 299 300 // Avoid looking up the localizedLevelName twice if we already 301 // have it. 302 final String getCachedLocalizedLevelName() { 303 304 if (localizedLevelName != null) { 305 if (cachedLocale != null) { 306 if (cachedLocale.equals(Locale.getDefault())) { 307 // OK: our cached value was looked up with the same 308 // locale. We can use it. 309 return localizedLevelName; 310 } 311 } 312 } 313 314 if (resourceBundleName == null) { 315 // No resource bundle: just use the name. 316 return name; 317 } 318 319 // We need to compute the localized name. 320 // Either because it's the first time, or because our cached 321 // value is for a different locale. Just return null. 322 return null; 323 } 324 325 final synchronized String getLocalizedLevelName() { 326 327 // See if we have a cached localized name 328 final String cachedLocalizedName = getCachedLocalizedLevelName(); 329 if (cachedLocalizedName != null) { 330 return cachedLocalizedName; 331 } 332 333 // No cached localized name or cache invalid. 334 // Need to compute the localized name. 335 final Locale newLocale = Locale.getDefault(); 336 try { 337 localizedLevelName = computeLocalizedLevelName(newLocale); 338 } catch (Exception ex) { 339 localizedLevelName = name; 340 } 341 cachedLocale = newLocale; 342 return localizedLevelName; 343 } 344 345 // Returns a mirrored Level object that matches the given name as 346 // specified in the Level.parse method. Returns null if not found. 347 // 348 // It returns the same Level object as the one returned by Level.parse 349 // method if the given name is a non-localized name or integer. 350 // 351 // If the name is a localized name, findLevel and parse method may 352 // return a different level value if there is a custom Level subclass 353 // that overrides Level.getLocalizedName() to return a different string 354 // than what's returned by the default implementation. 355 // 356 static Level findLevel(String name) { 357 if (name == null) { 358 throw new NullPointerException(); 359 } 360 361 Optional<Level> level; 362 363 // Look for a known Level with the given non-localized name. 364 level = KnownLevel.findByName(name, KnownLevel::mirrored); 365 if (level.isPresent()) { 366 return level.get(); 367 } 368 369 // Now, check if the given name is an integer. If so, 370 // first look for a Level with the given value and then 371 // if necessary create one. 372 try { 373 int x = Integer.parseInt(name); 374 level = KnownLevel.findByValue(x, KnownLevel::mirrored); 375 if (!level.isPresent()) { 376 // add new Level 377 Level levelObject = new Level(name, x); 378 return KnownLevel.findByValue(x, KnownLevel::mirrored).get(); 379 } 380 } catch (NumberFormatException ex) { 381 // Not an integer. 382 // Drop through. 383 } 384 385 level = KnownLevel.findByLocalizedLevelName(name, 386 KnownLevel::mirrored); 387 if (level.isPresent()) { 388 return level.get(); 389 } 390 391 return null; 392 } 393 394 /** 395 * Returns a string representation of this Level. 396 * 397 * @return the non-localized name of the Level, for example "INFO". 398 */ 399 @Override 400 public final String toString() { 401 return name; 402 } 403 404 /** 405 * Get the integer value for this level. This integer value 406 * can be used for efficient ordering comparisons between 407 * Level objects. 408 * @return the integer value for this level. 409 */ 410 public final int intValue() { 411 return value; 412 } 413 414 private static final long serialVersionUID = -8176160795706313070L; 415 416 // Serialization magic to prevent "doppelgangers". 417 // This is a performance optimization. 418 private Object readResolve() { 419 Optional<Level> level = KnownLevel.matches(this); 420 if (level.isPresent()) { 421 return level.get(); 422 } 423 // Woops. Whoever sent us this object knows 424 // about a new log level. Add it to our list. 425 return new Level(this.name, this.value, this.resourceBundleName); 426 } 427 428 /** 429 * Parse a level name string into a Level. 430 * <p> 431 * The argument string may consist of either a level name 432 * or an integer value. 433 * <p> 434 * For example: 435 * <ul> 436 * <li> "SEVERE" 437 * <li> "1000" 438 * </ul> 439 * 440 * @param name string to be parsed 441 * @throws NullPointerException if the name is null 442 * @throws IllegalArgumentException if the value is not valid. 443 * Valid values are integers between <CODE>Integer.MIN_VALUE</CODE> 444 * and <CODE>Integer.MAX_VALUE</CODE>, and all known level names. 445 * Known names are the levels defined by this class (e.g., <CODE>FINE</CODE>, 446 * <CODE>FINER</CODE>, <CODE>FINEST</CODE>), or created by this class with 447 * appropriate package access, or new levels defined or created 448 * by subclasses. 449 * 450 * @return The parsed value. Passing an integer that corresponds to a known name 451 * (e.g., 700) will return the associated name (e.g., <CODE>CONFIG</CODE>). 452 * Passing an integer that does not (e.g., 1) will return a new level name 453 * initialized to that value. 454 */ 455 public static synchronized Level parse(String name) throws IllegalArgumentException { 456 // Check that name is not null. 457 name.length(); 458 459 Optional<Level> level; 460 461 // Look for a known Level with the given non-localized name. 462 level = KnownLevel.findByName(name, KnownLevel::referent); 463 if (level.isPresent()) { 464 return level.get(); 465 } 466 467 // Now, check if the given name is an integer. If so, 468 // first look for a Level with the given value and then 469 // if necessary create one. 470 try { 471 int x = Integer.parseInt(name); 472 level = KnownLevel.findByValue(x, KnownLevel::referent); 473 if (level.isPresent()) { 474 return level.get(); 475 } 476 // add new Level. 477 Level levelObject = new Level(name, x); 478 return KnownLevel.findByValue(x, KnownLevel::referent).get(); 479 } catch (NumberFormatException ex) { 480 // Not an integer. 481 // Drop through. 482 } 483 484 // Finally, look for a known level with the given localized name, 485 // in the current default locale. 486 // This is relatively expensive, but not excessively so. 487 level = KnownLevel.findByLocalizedLevelName(name, KnownLevel::referent); 488 if (level .isPresent()) { 489 return level.get(); 490 } 491 492 // OK, we've tried everything and failed 493 throw new IllegalArgumentException("Bad level \"" + name + "\""); 494 } 495 496 /** 497 * Compare two objects for value equality. 498 * @return true if and only if the two objects have the same level value. 499 */ 500 @Override 501 public boolean equals(Object ox) { 502 try { 503 Level lx = (Level)ox; 504 return (lx.value == this.value); 505 } catch (Exception ex) { 506 return false; 507 } 508 } 509 510 /** 511 * Generate a hashcode. 512 * @return a hashcode based on the level value 513 */ 514 @Override 515 public int hashCode() { 516 return this.value; 517 } 518 519 // KnownLevel class maintains the global list of all known levels. 520 // The API allows multiple custom Level instances of the same name/value 521 // be created. This class provides convenient methods to find a level 522 // by a given name, by a given value, or by a given localized name. 523 // 524 // KnownLevel wraps the following Level objects: 525 // 1. levelObject: standard Level object or custom Level object 526 // 2. mirroredLevel: Level object representing the level specified in the 527 // logging configuration. 528 // 529 // Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods 530 // are non-final but the name and resource bundle name are parameters to 531 // the Level constructor. Use the mirroredLevel object instead of the 532 // levelObject to prevent the logging framework to execute foreign code 533 // implemented by untrusted Level subclass. 534 // 535 // Implementation Notes: 536 // If Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods 537 // were final, the following KnownLevel implementation can be removed. 538 // Future API change should take this into consideration. 539 static final class KnownLevel extends WeakReference<Level> { 540 private static Map<String, List<KnownLevel>> nameToLevels = new HashMap<>(); 541 private static Map<Integer, List<KnownLevel>> intToLevels = new HashMap<>(); 542 private static final ReferenceQueue<Level> QUEUE = new ReferenceQueue<>(); 543 544 final Level mirroredLevel; // mirror of the custom Level 545 KnownLevel(Level l) { 546 super(l, QUEUE); 547 if (l.getClass() == Level.class) { 548 this.mirroredLevel = l; 549 } else { 550 // this mirrored level object is hidden 551 this.mirroredLevel = new Level(l.name, l.value, 552 l.resourceBundleName, false); 553 } 554 } 555 556 Stream<Level> mirrored() { 557 return Stream.of(mirroredLevel); 558 } 559 560 Stream<Level> referent() { 561 final Level ref = get(); 562 return ref == null ? Stream.empty() : Stream.of(ref); 563 } 564 565 private void remove() { 566 Optional.ofNullable(nameToLevels.get(mirroredLevel.name)) 567 .ifPresent((x) -> x.remove(this)); 568 Optional.ofNullable(intToLevels.get(mirroredLevel.value)) 569 .ifPresent((x) -> x.remove(this)); 570 } 571 572 // Remove all stale KnownLevel instances 573 static synchronized void purge() { 574 Reference<? extends Level> ref; 575 while ((ref = QUEUE.poll()) != null) { 576 if (ref instanceof KnownLevel) { 577 ((KnownLevel)ref).remove(); 578 } 579 } 580 } 581 582 static synchronized void add(Level l) { 583 purge(); 584 // the mirroredLevel object is always added to the list 585 // before the custom Level instance 586 KnownLevel o = new KnownLevel(l); 587 List<KnownLevel> list = nameToLevels.get(l.name); 588 if (list == null) { 589 list = new ArrayList<>(); 590 nameToLevels.put(l.name, list); 591 } 592 list.add(o); 593 594 list = intToLevels.get(l.value); 595 if (list == null) { 596 list = new ArrayList<>(); 597 intToLevels.put(l.value, list); 598 } 599 list.add(o); 600 } 601 602 // Returns a KnownLevel with the given non-localized name. 603 static synchronized Optional<Level> findByName(String name, 604 Function<KnownLevel, Stream<Level>> selector) { 605 purge(); 606 return nameToLevels.getOrDefault(name, Collections.emptyList()) 607 .stream() 608 .flatMap(selector) 609 .findFirst(); 610 } 611 612 // Returns a KnownLevel with the given value. 613 static synchronized Optional<Level> findByValue(int value, 614 Function<KnownLevel, Stream<Level>> selector) { 615 purge(); 616 return intToLevels.getOrDefault(value, Collections.emptyList()) 617 .stream() 618 .flatMap(selector) 619 .findFirst(); 620 } 621 622 // Returns a KnownLevel with the given localized name matching 623 // by calling the Level.getLocalizedLevelName() method (i.e. found 624 // from the resourceBundle associated with the Level object). 625 // This method does not call Level.getLocalizedName() that may 626 // be overridden in a subclass implementation 627 static synchronized Optional<Level> findByLocalizedLevelName(String name, 628 Function<KnownLevel, Stream<Level>> selector) { 629 purge(); 630 return nameToLevels.values() 631 .stream() 632 .flatMap(List::stream) 633 .flatMap(selector) 634 .filter(lo -> name.equals(lo.getLocalizedLevelName())) 635 .findFirst(); 636 } 637 638 static synchronized Optional<Level> matches(Level l) { 639 purge(); 640 List<KnownLevel> list = nameToLevels.get(l.name); 641 if (list != null) { 642 for (KnownLevel ref : list) { 643 Level levelObject = ref.get(); 644 if (levelObject == null) continue; 645 Level other = ref.mirroredLevel; 646 if (l.value == other.value && 647 (l.resourceBundleName == other.resourceBundleName || 648 (l.resourceBundleName != null && 649 l.resourceBundleName.equals(other.resourceBundleName)))) { 650 return Optional.of(levelObject); 651 } 652 } 653 } 654 return Optional.empty(); 655 } 656 } 657 658 }