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