1 /* 2 * Copyright (c) 2000, 2015, 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.time.Instant; 28 import java.util.*; 29 import java.util.concurrent.atomic.AtomicInteger; 30 import java.util.concurrent.atomic.AtomicLong; 31 import java.io.*; 32 import java.security.AccessController; 33 import java.security.PrivilegedAction; 34 import java.time.Clock; 35 import java.util.function.Predicate; 36 37 import static jdk.internal.logger.SimpleConsoleLogger.isFilteredFrame; 38 39 /** 40 * LogRecord objects are used to pass logging requests between 41 * the logging framework and individual log Handlers. 42 * <p> 43 * When a LogRecord is passed into the logging framework it 44 * logically belongs to the framework and should no longer be 45 * used or updated by the client application. 46 * <p> 47 * Note that if the client application has not specified an 48 * explicit source method name and source class name, then the 49 * LogRecord class will infer them automatically when they are 50 * first accessed (due to a call on getSourceMethodName or 51 * getSourceClassName) by analyzing the call stack. Therefore, 52 * if a logging Handler wants to pass off a LogRecord to another 53 * thread, or to transmit it over RMI, and if it wishes to subsequently 54 * obtain method name or class name information it should call 55 * one of getSourceClassName or getSourceMethodName to force 56 * the values to be filled in. 57 * <p> 58 * <b> Serialization notes:</b> 59 * <ul> 60 * <li>The LogRecord class is serializable. 61 * 62 * <li> Because objects in the parameters array may not be serializable, 63 * during serialization all objects in the parameters array are 64 * written as the corresponding Strings (using Object.toString). 65 * 66 * <li> The ResourceBundle is not transmitted as part of the serialized 67 * form, but the resource bundle name is, and the recipient object's 68 * readObject method will attempt to locate a suitable resource bundle. 69 * 70 * </ul> 71 * 72 * @since 1.4 73 */ 74 75 public class LogRecord implements java.io.Serializable { 76 private static final AtomicLong globalSequenceNumber 77 = new AtomicLong(0); 78 79 /** 80 * The default value of threadID will be the current thread's 81 * thread id, for ease of correlation, unless it is greater than 82 * MIN_SEQUENTIAL_THREAD_ID, in which case we try harder to keep 83 * our promise to keep threadIDs unique by avoiding collisions due 84 * to 32-bit wraparound. Unfortunately, LogRecord.getThreadID() 85 * returns int, while Thread.getId() returns long. 86 */ 87 private static final int MIN_SEQUENTIAL_THREAD_ID = Integer.MAX_VALUE / 2; 88 89 private static final AtomicInteger nextThreadId 90 = new AtomicInteger(MIN_SEQUENTIAL_THREAD_ID); 91 92 private static final ThreadLocal<Integer> threadIds = new ThreadLocal<>(); 93 94 /** 95 * Logging message level 96 */ 97 private Level level; 98 99 /** 100 * Sequence number 101 */ 102 private long sequenceNumber; 103 104 /** 105 * Class that issued logging call 106 */ 107 private String sourceClassName; 108 109 /** 110 * Method that issued logging call 111 */ 112 private String sourceMethodName; 113 114 /** 115 * Non-localized raw message text 116 */ 117 private String message; 118 119 /** 120 * Thread ID for thread that issued logging call. 121 */ 122 private int threadID; 123 124 /** 125 * The Throwable (if any) associated with log message 126 */ 127 private Throwable thrown; 128 129 /** 130 * Name of the source Logger. 131 */ 132 private String loggerName; 133 134 /** 135 * Resource bundle name to localized log message. 136 */ 137 private String resourceBundleName; 138 139 /** 140 * Event time. 141 * @since 9 142 */ 143 private Instant instant; 144 145 /** 146 * @serialField level Level Logging message level 147 * @serialField sequenceNumber long Sequence number 148 * @serialField sourceClassName String Class that issued logging call 149 * @serialField sourceMethodName String Method that issued logging call 150 * @serialField message String Non-localized raw message text 151 * @serialField threadID int Thread ID for thread that issued logging call 152 * @serialField millis long Truncated event time in milliseconds since 1970 153 * - calculated as getInstant().toEpochMilli(). 154 * The event time instant can be reconstructed using 155 * <code>Instant.ofEpochSecond(millis/1000, (millis % 1000) * 1000_000 + nanoAdjustment)</code> 156 * @serialField nanoAdjustment int Nanoseconds adjustment to the millisecond of 157 * event time - calculated as getInstant().getNano() % 1000_000 158 * The event time instant can be reconstructed using 159 * <code>Instant.ofEpochSecond(millis/1000, (millis % 1000) * 1000_000 + nanoAdjustment)</code> 160 * <p> 161 * Since: 9 162 * @serialField thrown Throwable The Throwable (if any) associated with log 163 * message 164 * @serialField loggerName String Name of the source Logger 165 * @serialField resourceBundleName String Resource bundle name to localized 166 * log message 167 */ 168 private static final ObjectStreamField[] serialPersistentFields = 169 new ObjectStreamField[] { 170 new ObjectStreamField("level", Level.class), 171 new ObjectStreamField("sequenceNumber", long.class), 172 new ObjectStreamField("sourceClassName", String.class), 173 new ObjectStreamField("sourceMethodName", String.class), 174 new ObjectStreamField("message", String.class), 175 new ObjectStreamField("threadID", int.class), 176 new ObjectStreamField("millis", long.class), 177 new ObjectStreamField("nanoAdjustment", int.class), 178 new ObjectStreamField("thrown", Throwable.class), 179 new ObjectStreamField("loggerName", String.class), 180 new ObjectStreamField("resourceBundleName", String.class), 181 }; 182 183 private transient boolean needToInferCaller; 184 private transient Object parameters[]; 185 private transient ResourceBundle resourceBundle; 186 187 /** 188 * Returns the default value for a new LogRecord's threadID. 189 */ 190 private int defaultThreadID() { 191 long tid = Thread.currentThread().getId(); 192 if (tid < MIN_SEQUENTIAL_THREAD_ID) { 193 return (int) tid; 194 } else { 195 Integer id = threadIds.get(); 196 if (id == null) { 197 id = nextThreadId.getAndIncrement(); 198 threadIds.set(id); 199 } 200 return id; 201 } 202 } 203 204 /** 205 * Construct a LogRecord with the given level and message values. 206 * <p> 207 * The sequence property will be initialized with a new unique value. 208 * These sequence values are allocated in increasing order within a VM. 209 * <p> 210 * Since JDK 9, the event time is represented by an {@link Instant}. 211 * The instant property will be initialized to the {@linkplain 212 * Instant#now() current instant}, using the best available 213 * {@linkplain Clock#systemUTC() clock} on the system. 214 * <p> 215 * The thread ID property will be initialized with a unique ID for 216 * the current thread. 217 * <p> 218 * All other properties will be initialized to "null". 219 * 220 * @param level a logging level value 221 * @param msg the raw non-localized logging message (may be null) 222 * @see java.time.Clock#systemUTC() 223 */ 224 public LogRecord(Level level, String msg) { 225 this.level = Objects.requireNonNull(level); 226 message = msg; 227 // Assign a thread ID and a unique sequence number. 228 sequenceNumber = globalSequenceNumber.getAndIncrement(); 229 threadID = defaultThreadID(); 230 instant = Instant.now(); 231 needToInferCaller = true; 232 } 233 234 /** 235 * Get the source Logger's name. 236 * 237 * @return source logger name (may be null) 238 */ 239 public String getLoggerName() { 240 return loggerName; 241 } 242 243 /** 244 * Set the source Logger's name. 245 * 246 * @param name the source logger name (may be null) 247 */ 248 public void setLoggerName(String name) { 249 loggerName = name; 250 } 251 252 /** 253 * Get the localization resource bundle 254 * <p> 255 * This is the ResourceBundle that should be used to localize 256 * the message string before formatting it. The result may 257 * be null if the message is not localizable, or if no suitable 258 * ResourceBundle is available. 259 * @return the localization resource bundle 260 */ 261 public ResourceBundle getResourceBundle() { 262 return resourceBundle; 263 } 264 265 /** 266 * Set the localization resource bundle. 267 * 268 * @param bundle localization bundle (may be null) 269 */ 270 public void setResourceBundle(ResourceBundle bundle) { 271 resourceBundle = bundle; 272 } 273 274 /** 275 * Get the localization resource bundle name 276 * <p> 277 * This is the name for the ResourceBundle that should be 278 * used to localize the message string before formatting it. 279 * The result may be null if the message is not localizable. 280 * @return the localization resource bundle name 281 */ 282 public String getResourceBundleName() { 283 return resourceBundleName; 284 } 285 286 /** 287 * Set the localization resource bundle name. 288 * 289 * @param name localization bundle name (may be null) 290 */ 291 public void setResourceBundleName(String name) { 292 resourceBundleName = name; 293 } 294 295 /** 296 * Get the logging message level, for example Level.SEVERE. 297 * @return the logging message level 298 */ 299 public Level getLevel() { 300 return level; 301 } 302 303 /** 304 * Set the logging message level, for example Level.SEVERE. 305 * @param level the logging message level 306 */ 307 public void setLevel(Level level) { 308 if (level == null) { 309 throw new NullPointerException(); 310 } 311 this.level = level; 312 } 313 314 /** 315 * Get the sequence number. 316 * <p> 317 * Sequence numbers are normally assigned in the LogRecord 318 * constructor, which assigns unique sequence numbers to 319 * each new LogRecord in increasing order. 320 * @return the sequence number 321 */ 322 public long getSequenceNumber() { 323 return sequenceNumber; 324 } 325 326 /** 327 * Set the sequence number. 328 * <p> 329 * Sequence numbers are normally assigned in the LogRecord constructor, 330 * so it should not normally be necessary to use this method. 331 * @param seq the sequence number 332 */ 333 public void setSequenceNumber(long seq) { 334 sequenceNumber = seq; 335 } 336 337 /** 338 * Get the name of the class that (allegedly) issued the logging request. 339 * <p> 340 * Note that this sourceClassName is not verified and may be spoofed. 341 * This information may either have been provided as part of the 342 * logging call, or it may have been inferred automatically by the 343 * logging framework. In the latter case, the information may only 344 * be approximate and may in fact describe an earlier call on the 345 * stack frame. 346 * <p> 347 * May be null if no information could be obtained. 348 * 349 * @return the source class name 350 */ 351 public String getSourceClassName() { 352 if (needToInferCaller) { 353 inferCaller(); 354 } 355 return sourceClassName; 356 } 357 358 /** 359 * Set the name of the class that (allegedly) issued the logging request. 360 * 361 * @param sourceClassName the source class name (may be null) 362 */ 363 public void setSourceClassName(String sourceClassName) { 364 this.sourceClassName = sourceClassName; 365 needToInferCaller = false; 366 } 367 368 /** 369 * Get the name of the method that (allegedly) issued the logging request. 370 * <p> 371 * Note that this sourceMethodName is not verified and may be spoofed. 372 * This information may either have been provided as part of the 373 * logging call, or it may have been inferred automatically by the 374 * logging framework. In the latter case, the information may only 375 * be approximate and may in fact describe an earlier call on the 376 * stack frame. 377 * <p> 378 * May be null if no information could be obtained. 379 * 380 * @return the source method name 381 */ 382 public String getSourceMethodName() { 383 if (needToInferCaller) { 384 inferCaller(); 385 } 386 return sourceMethodName; 387 } 388 389 /** 390 * Set the name of the method that (allegedly) issued the logging request. 391 * 392 * @param sourceMethodName the source method name (may be null) 393 */ 394 public void setSourceMethodName(String sourceMethodName) { 395 this.sourceMethodName = sourceMethodName; 396 needToInferCaller = false; 397 } 398 399 /** 400 * Get the "raw" log message, before localization or formatting. 401 * <p> 402 * May be null, which is equivalent to the empty string "". 403 * <p> 404 * This message may be either the final text or a localization key. 405 * <p> 406 * During formatting, if the source logger has a localization 407 * ResourceBundle and if that ResourceBundle has an entry for 408 * this message string, then the message string is replaced 409 * with the localized value. 410 * 411 * @return the raw message string 412 */ 413 public String getMessage() { 414 return message; 415 } 416 417 /** 418 * Set the "raw" log message, before localization or formatting. 419 * 420 * @param message the raw message string (may be null) 421 */ 422 public void setMessage(String message) { 423 this.message = message; 424 } 425 426 /** 427 * Get the parameters to the log message. 428 * 429 * @return the log message parameters. May be null if 430 * there are no parameters. 431 */ 432 public Object[] getParameters() { 433 return parameters; 434 } 435 436 /** 437 * Set the parameters to the log message. 438 * 439 * @param parameters the log message parameters. (may be null) 440 */ 441 public void setParameters(Object parameters[]) { 442 this.parameters = parameters; 443 } 444 445 /** 446 * Get an identifier for the thread where the message originated. 447 * <p> 448 * This is a thread identifier within the Java VM and may or 449 * may not map to any operating system ID. 450 * 451 * @return thread ID 452 */ 453 public int getThreadID() { 454 return threadID; 455 } 456 457 /** 458 * Set an identifier for the thread where the message originated. 459 * @param threadID the thread ID 460 */ 461 public void setThreadID(int threadID) { 462 this.threadID = threadID; 463 } 464 465 /** 466 * Get truncated event time in milliseconds since 1970. 467 * 468 * @return truncated event time in millis since 1970 469 * 470 * @implSpec This is equivalent to calling 471 * {@link #getInstant() getInstant().toEpochMilli()}. 472 * 473 * @apiNote To get the full nanosecond resolution event time, 474 * use {@link #getInstant()}. 475 * 476 * @see #getInstant() 477 */ 478 public long getMillis() { 479 return instant.toEpochMilli(); 480 } 481 482 /** 483 * Set event time. 484 * 485 * @param millis event time in millis since 1970. 486 * 487 * @implSpec This is equivalent to calling 488 * {@link #setInstant(java.time.Instant) 489 * setInstant(Instant.ofEpochMilli(millis))}. 490 * 491 * @deprecated LogRecord maintains timestamps with nanosecond resolution, 492 * using {@link Instant} values. For this reason, 493 * {@link #setInstant(java.time.Instant) setInstant()} 494 * should be used in preference to {@code setMillis()}. 495 * 496 * @see #setInstant(java.time.Instant) 497 */ 498 @Deprecated 499 public void setMillis(long millis) { 500 this.instant = Instant.ofEpochMilli(millis); 501 } 502 503 /** 504 * Gets the instant that the event occurred. 505 * 506 * @return the instant that the event occurred. 507 * 508 * @since 9 509 */ 510 public Instant getInstant() { 511 return instant; 512 } 513 514 /** 515 * Sets the instant that the event occurred. 516 * <p> 517 * If the given {@code instant} represents a point on the time-line too 518 * far in the future or past to fit in a {@code long} milliseconds and 519 * nanoseconds adjustment, then an {@code ArithmeticException} will be 520 * thrown. 521 * 522 * @param instant the instant that the event occurred. 523 * 524 * @throws NullPointerException if {@code instant} is null. 525 * @throws ArithmeticException if numeric overflow would occur while 526 * calling {@link Instant#toEpochMilli() instant.toEpochMilli()}. 527 * 528 * @since 9 529 */ 530 public void setInstant(Instant instant) { 531 instant.toEpochMilli(); 532 this.instant = instant; 533 } 534 535 /** 536 * Get any throwable associated with the log record. 537 * <p> 538 * If the event involved an exception, this will be the 539 * exception object. Otherwise null. 540 * 541 * @return a throwable 542 */ 543 public Throwable getThrown() { 544 return thrown; 545 } 546 547 /** 548 * Set a throwable associated with the log event. 549 * 550 * @param thrown a throwable (may be null) 551 */ 552 public void setThrown(Throwable thrown) { 553 this.thrown = thrown; 554 } 555 556 private static final long serialVersionUID = 5372048053134512534L; 557 558 /** 559 * @serialData Serialized fields, followed by a two byte version number 560 * (major byte, followed by minor byte), followed by information on 561 * the log record parameter array. If there is no parameter array, 562 * then -1 is written. If there is a parameter array (possible of zero 563 * length) then the array length is written as an integer, followed 564 * by String values for each parameter. If a parameter is null, then 565 * a null String is written. Otherwise the output of Object.toString() 566 * is written. 567 */ 568 private void writeObject(ObjectOutputStream out) throws IOException { 569 // We have to write serialized fields first. 570 ObjectOutputStream.PutField pf = out.putFields(); 571 pf.put("level", level); 572 pf.put("sequenceNumber", sequenceNumber); 573 pf.put("sourceClassName", sourceClassName); 574 pf.put("sourceMethodName", sourceMethodName); 575 pf.put("message", message); 576 pf.put("threadID", threadID); 577 pf.put("millis", instant.toEpochMilli()); 578 pf.put("nanoAdjustment", instant.getNano() % 1000_000); 579 pf.put("thrown", thrown); 580 pf.put("loggerName", loggerName); 581 pf.put("resourceBundleName", resourceBundleName); 582 out.writeFields(); 583 584 // Write our version number. 585 out.writeByte(1); 586 out.writeByte(0); 587 if (parameters == null) { 588 out.writeInt(-1); 589 return; 590 } 591 out.writeInt(parameters.length); 592 // Write string values for the parameters. 593 for (Object parameter : parameters) { 594 out.writeObject(Objects.toString(parameter, null)); 595 } 596 } 597 598 private void readObject(ObjectInputStream in) 599 throws IOException, ClassNotFoundException { 600 // We have to read serialized fields first. 601 ObjectInputStream.GetField gf = in.readFields(); 602 level = (Level) gf.get("level", null); 603 sequenceNumber = gf.get("sequenceNumber", 0L); 604 sourceClassName = (String) gf.get("sourceClassName", null); 605 sourceMethodName = (String) gf.get("sourceMethodName", null); 606 message = (String) gf.get("message", null); 607 threadID = gf.get("threadID", 0); 608 long millis = gf.get("millis", 0L); 609 int nanoOfMilli = gf.get("nanoAdjustment", 0); 610 instant = Instant.ofEpochSecond( 611 millis / 1000L, (millis % 1000L) * 1000_000L + nanoOfMilli); 612 thrown = (Throwable) gf.get("thrown", null); 613 loggerName = (String) gf.get("loggerName", null); 614 resourceBundleName = (String) gf.get("resourceBundleName", null); 615 616 // Read version number. 617 byte major = in.readByte(); 618 byte minor = in.readByte(); 619 if (major != 1) { 620 throw new IOException("LogRecord: bad version: " + major + "." + minor); 621 } 622 int len = in.readInt(); 623 if (len == -1) { 624 parameters = null; 625 } else { 626 parameters = new Object[len]; 627 for (int i = 0; i < parameters.length; i++) { 628 parameters[i] = in.readObject(); 629 } 630 } 631 // If necessary, try to regenerate the resource bundle. 632 if (resourceBundleName != null) { 633 try { 634 // use system class loader to ensure the ResourceBundle 635 // instance is a different instance than null loader uses 636 final ResourceBundle bundle = 637 ResourceBundle.getBundle(resourceBundleName, 638 Locale.getDefault(), 639 ClassLoader.getSystemClassLoader()); 640 resourceBundle = bundle; 641 } catch (MissingResourceException ex) { 642 // This is not a good place to throw an exception, 643 // so we simply leave the resourceBundle null. 644 resourceBundle = null; 645 } 646 } 647 648 needToInferCaller = false; 649 } 650 651 // Private method to infer the caller's class and method names 652 // 653 // Note: 654 // For testing purposes - it is possible to customize the process 655 // by which LogRecord will infer the source class name and source method name 656 // when analyzing the call stack. 657 // <p> 658 // The system property {@code jdk.logger.packages} can define a comma separated 659 // list of strings corresponding to additional package name prefixes that 660 // should be ignored when trying to infer the source caller class name. 661 // Those stack frames whose {@linkplain StackTraceElement#getClassName() 662 // declaring class name} start with one such prefix will be ignored. 663 // <p> 664 // This is primarily useful when providing utility logging classes wrapping 665 // a logger instance, as it makes it possible to instruct LogRecord to skip 666 // those utility frames when inferring the caller source class name. 667 // <p> 668 // The {@code jdk.logger.packages} system property is consulted only once. 669 // <p> 670 // This property is not standard, implementation specific, and yet 671 // undocumented (and thus subject to changes without notice). 672 // 673 private void inferCaller() { 674 needToInferCaller = false; 675 // Skip all frames until we have found the first logger frame. 676 Optional<StackWalker.StackFrame> frame = new CallerFinder().get(); 677 frame.ifPresent(f -> { 678 setSourceClassName(f.getClassName()); 679 setSourceMethodName(f.getMethodName()); 680 }); 681 682 // We haven't found a suitable frame, so just punt. This is 683 // OK as we are only committed to making a "best effort" here. 684 } 685 686 /* 687 * CallerFinder is a stateful predicate. 688 */ 689 static final class CallerFinder implements Predicate<StackWalker.StackFrame> { 690 private static final StackWalker WALKER; 691 static { 692 final PrivilegedAction<StackWalker> action = 693 () -> StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE); 694 WALKER = AccessController.doPrivileged(action); 695 } 696 697 /** 698 * Returns StackFrame of the caller's frame. 699 * @return StackFrame of the caller's frame. 700 */ 701 Optional<StackWalker.StackFrame> get() { 702 return WALKER.walk((s) -> s.filter(this).findFirst()); 703 } 704 705 private boolean lookingForLogger = true; 706 /** 707 * Returns true if we have found the caller's frame, false if the frame 708 * must be skipped. 709 * 710 * @param t The frame info. 711 * @return true if we have found the caller's frame, false if the frame 712 * must be skipped. 713 */ 714 @Override 715 public boolean test(StackWalker.StackFrame t) { 716 final String cname = t.getClassName(); 717 // We should skip all frames until we have found the logger, 718 // because these frames could be frames introduced by e.g. custom 719 // sub classes of Handler. 720 if (lookingForLogger) { 721 // the log record could be created for a platform logger 722 lookingForLogger = !isLoggerImplFrame(cname); 723 return false; 724 } 725 // Continue walking until we've found the relevant calling frame. 726 // Skips logging/logger infrastructure. 727 return !isFilteredFrame(t); 728 } 729 730 private boolean isLoggerImplFrame(String cname) { 731 return (cname.equals("java.util.logging.Logger") || 732 cname.startsWith("sun.util.logging.PlatformLogger")); 733 } 734 } 735 }