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.time.Clock;
  33 
  34 import jdk.internal.misc.JavaLangAccess;
  35 import jdk.internal.misc.SharedSecrets;
  36 import static jdk.internal.logger.SimpleConsoleLogger.skipLoggingFrame;
  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 1.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: 1.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 1.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      * @deprecated To get the full nanosecond resolution event time,
 473      *             use {@link #getInstant()}.
 474      *
 475      * @see #getInstant()
 476      */
 477     @Deprecated
 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 To set event time with nanosecond resolution,
 492      *             use {@link #setInstant(java.time.Instant)}.
 493      *
 494      * @see #setInstant(java.time.Instant)
 495      */
 496     @Deprecated
 497     public void setMillis(long millis) {
 498         this.instant = Instant.ofEpochMilli(millis);
 499     }
 500 
 501     /**
 502      * Gets the instant that the event occurred.
 503      *
 504      * @return the instant that the event occurred.
 505      *
 506      * @since 1.9
 507      */
 508     public Instant getInstant() {
 509         return instant;
 510     }
 511 
 512     /**
 513      * Sets the instant that the event occurred.
 514      *
 515      * @param instant the instant that the event occurred.
 516      *
 517      * @throws NullPointerException if {@code instant} is null.
 518      * @since 1.9
 519      */
 520     public void setInstant(Instant instant) {
 521         this.instant = Objects.requireNonNull(instant);
 522     }
 523 
 524     /**
 525      * Get any throwable associated with the log record.
 526      * <p>
 527      * If the event involved an exception, this will be the
 528      * exception object. Otherwise null.
 529      *
 530      * @return a throwable
 531      */
 532     public Throwable getThrown() {
 533         return thrown;
 534     }
 535 
 536     /**
 537      * Set a throwable associated with the log event.
 538      *
 539      * @param thrown  a throwable (may be null)
 540      */
 541     public void setThrown(Throwable thrown) {
 542         this.thrown = thrown;
 543     }
 544 
 545     private static final long serialVersionUID = 5372048053134512534L;
 546 
 547     /**
 548      * @serialData Serialized fields, followed by a two byte version number
 549      * (major byte, followed by minor byte), followed by information on
 550      * the log record parameter array.  If there is no parameter array,
 551      * then -1 is written.  If there is a parameter array (possible of zero
 552      * length) then the array length is written as an integer, followed
 553      * by String values for each parameter.  If a parameter is null, then
 554      * a null String is written.  Otherwise the output of Object.toString()
 555      * is written.
 556      */
 557     private void writeObject(ObjectOutputStream out) throws IOException {
 558         // We have to write serialized fields first.
 559         ObjectOutputStream.PutField pf = out.putFields();
 560         pf.put("level", level);
 561         pf.put("sequenceNumber", sequenceNumber);
 562         pf.put("sourceClassName", sourceClassName);
 563         pf.put("sourceMethodName", sourceMethodName);
 564         pf.put("message", message);
 565         pf.put("threadID", threadID);
 566         pf.put("millis", instant.toEpochMilli());
 567         pf.put("nanoAdjustment", instant.getNano() % 1000_000);
 568         pf.put("thrown", thrown);
 569         pf.put("loggerName", loggerName);
 570         pf.put("resourceBundleName", resourceBundleName);
 571         out.writeFields();
 572 
 573         // Write our version number.
 574         out.writeByte(1);
 575         out.writeByte(0);
 576         if (parameters == null) {
 577             out.writeInt(-1);
 578             return;
 579         }
 580         out.writeInt(parameters.length);
 581         // Write string values for the parameters.
 582         for (Object parameter : parameters) {
 583             out.writeObject(Objects.toString(parameter, null));
 584         }
 585     }
 586 
 587     private void readObject(ObjectInputStream in)
 588                         throws IOException, ClassNotFoundException {
 589         // We have to read serialized fields first.
 590         ObjectInputStream.GetField gf = in.readFields();
 591         level = (Level) gf.get("level", null);
 592         sequenceNumber = gf.get("sequenceNumber", 0L);
 593         sourceClassName = (String) gf.get("sourceClassName", null);
 594         sourceMethodName = (String) gf.get("sourceMethodName", null);
 595         message = (String) gf.get("message", null);
 596         threadID = gf.get("threadID", 0);
 597         long millis = gf.get("millis", 0L);
 598         int nanoOfMilli = gf.get("nanoAdjustment", 0);
 599         instant = Instant.ofEpochSecond(
 600             millis / 1000L, (millis % 1000L) * 1000_000L + nanoOfMilli);
 601         thrown = (Throwable) gf.get("thrown", null);
 602         loggerName = (String) gf.get("loggerName", null);
 603         resourceBundleName = (String) gf.get("resourceBundleName", null);
 604 
 605         // Read version number.
 606         byte major = in.readByte();
 607         byte minor = in.readByte();
 608         if (major != 1) {
 609             throw new IOException("LogRecord: bad version: " + major + "." + minor);
 610         }
 611         int len = in.readInt();
 612         if (len == -1) {
 613             parameters = null;
 614         } else {
 615             parameters = new Object[len];
 616             for (int i = 0; i < parameters.length; i++) {
 617                 parameters[i] = in.readObject();
 618             }
 619         }
 620         // If necessary, try to regenerate the resource bundle.
 621         if (resourceBundleName != null) {
 622             try {
 623                 // use system class loader to ensure the ResourceBundle
 624                 // instance is a different instance than null loader uses
 625                 final ResourceBundle bundle =
 626                         ResourceBundle.getBundle(resourceBundleName,
 627                                 Locale.getDefault(),
 628                                 ClassLoader.getSystemClassLoader());
 629                 resourceBundle = bundle;
 630             } catch (MissingResourceException ex) {
 631                 // This is not a good place to throw an exception,
 632                 // so we simply leave the resourceBundle null.
 633                 resourceBundle = null;
 634             }
 635         }
 636 
 637         needToInferCaller = false;
 638     }
 639 
 640     // Private method to infer the caller's class and method names
 641     //
 642     // Note:
 643     // For testing purposes - it is possible to customize the process
 644     // by which LogRecord will infer the source class name and source method name
 645     // when analyzing the call stack.
 646     // <p>
 647     // The system property {@code jdk.logger.packages} can define a comma separated
 648     // list of strings corresponding to additional package name prefixes that
 649     // should be ignored when trying to infer the source caller class name.
 650     // Those stack frames whose {@linkplain StackTraceElement#getClassName()
 651     // declaring class name} start with one such prefix will be ignored.
 652     // <p>
 653     // This is primarily useful when providing utility logging classes wrapping
 654     // a logger instance, as it makes it possible to instruct LogRecord to skip
 655     // those utility frames when inferring the caller source class name.
 656     // <p>
 657     // The {@code jdk.logger.packages} system property is consulted only once.
 658     // <p>
 659     // This property is not standard, implementation specific, and yet
 660     // undocumented (and thus subject to changes without notice).
 661     //
 662     private void inferCaller() {
 663         needToInferCaller = false;
 664         JavaLangAccess access = SharedSecrets.getJavaLangAccess();
 665         Throwable throwable = new Throwable();
 666         int depth = access.getStackTraceDepth(throwable);
 667 
 668         boolean lookingForLogger = true;
 669         for (int ix = 0; ix < depth; ix++) {
 670             // Calling getStackTraceElement directly prevents the VM
 671             // from paying the cost of building the entire stack frame.
 672             StackTraceElement frame =
 673                 access.getStackTraceElement(throwable, ix);
 674             String cname = frame.getClassName();
 675             boolean isLoggerImpl = isLoggerImplFrame(cname);
 676             if (lookingForLogger) {
 677                 // Skip all frames until we have found the first logger frame.
 678                 if (isLoggerImpl) {
 679                     lookingForLogger = false;
 680                 }
 681             } else {
 682                 if (!isLoggerImpl) {
 683                     // skip logging/logger infrastructure and reflection calls
 684                     if (!skipLoggingFrame(cname)) {
 685                        // We've found the relevant frame.
 686                        setSourceClassName(cname);
 687                        setSourceMethodName(frame.getMethodName());
 688                        return;
 689                     }
 690                 }
 691             }
 692         }
 693         // We haven't found a suitable frame, so just punt.  This is
 694         // OK as we are only committed to making a "best effort" here.
 695     }
 696 
 697     private boolean isLoggerImplFrame(String cname) {
 698         // the log record could be created for a platform logger
 699         return (cname.equals("java.util.logging.Logger") ||
 700                 cname.startsWith("sun.util.logging.PlatformLogger"));
 701     }
 702 }