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