1 /*
   2  * Copyright (c) 2000, 2020, 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 
  27 package java.util.logging;
  28 
  29 import java.io.*;
  30 import java.time.ZoneId;
  31 import java.time.ZonedDateTime;
  32 import jdk.internal.logger.SurrogateLogger;
  33 
  34 /**
  35  * Print a brief summary of the {@code LogRecord} in a human readable
  36  * format.  The summary will typically be 1 or 2 lines.
  37  *
  38  * <p>
  39  * <a id="formatting">
  40  * <b>Configuration:</b></a>
  41  * The {@code SimpleFormatter} is initialized with the format string
  42  * specified in the {@systemProperty java.util.logging.SimpleFormatter.format}
  43  * property to {@linkplain #format(LogRecord) format} the log messages.
  44  * This property can be defined
  45  * in the {@linkplain LogManager#getProperty logging properties}
  46  * configuration file
  47  * or as a system property.  If this property is set in both
  48  * the logging properties and system properties,
  49  * the format string specified in the system property will be used.
  50  * If this property is not defined or the given format string
  51  * is {@linkplain java.util.IllegalFormatException illegal},
  52  * the default format is implementation-specific.
  53  *
  54  * @since 1.4
  55  * @see java.util.Formatter
  56  */
  57 
  58 public class SimpleFormatter extends Formatter {
  59 
  60     // format string for printing the log record
  61     static String getLoggingProperty(String name) {
  62         return LogManager.getLogManager().getProperty(name);
  63     }
  64 
  65     private final String format =
  66         SurrogateLogger.getSimpleFormat(SimpleFormatter::getLoggingProperty);
  67 
  68     /**
  69      * Create a {@code SimpleFormatter}.
  70      */
  71     public SimpleFormatter() {}
  72 
  73     /**
  74      * Format the given LogRecord.
  75      * <p>
  76      * The formatting can be customized by specifying the format string
  77      * in the <a href="#formatting">
  78      * {@code java.util.logging.SimpleFormatter.format}</a> property.
  79      * The given {@code LogRecord} will be formatted as if by calling:
  80      * <pre>
  81      *    {@link String#format String.format}(format, date, source, logger, level, message, thrown);
  82      * </pre>
  83      * where the arguments are:<br>
  84      * <ol>
  85      * <li>{@code format} - the {@link java.util.Formatter
  86      *     java.util.Formatter} format string specified in the
  87      *     {@code java.util.logging.SimpleFormatter.format} property
  88      *     or the default format.</li>
  89      * <li>{@code date} - a {@link ZonedDateTime} object representing
  90      *     {@linkplain LogRecord#getInstant() event time} of the log record
  91      *      in the {@link ZoneId#systemDefault()} system time zone.</li>
  92      * <li>{@code source} - a string representing the caller, if available;
  93      *     otherwise, the logger's name.</li>
  94      * <li>{@code logger} - the logger's name.</li>
  95      * <li>{@code level} - the {@linkplain Level#getLocalizedName
  96      *     log level}.</li>
  97      * <li>{@code message} - the formatted log message
  98      *     returned from the {@link Formatter#formatMessage(LogRecord)}
  99      *     method.  It uses {@link java.text.MessageFormat java.text}
 100      *     formatting and does not use the {@code java.util.Formatter
 101      *     format} argument.</li>
 102      * <li>{@code thrown} - a string representing
 103      *     the {@linkplain LogRecord#getThrown throwable}
 104      *     associated with the log record and its backtrace
 105      *     beginning with a newline character, if any;
 106      *     otherwise, an empty string.</li>
 107      * </ol>
 108      *
 109      * <p>Some example formats:<br>
 110      * <ul>
 111      * <li> {@code java.util.logging.SimpleFormatter.format="%4$s: %5$s [%1$tc]%n"}
 112      *     <p>This prints 1 line with the log level ({@code 4$}),
 113      *     the log message ({@code 5$}) and the timestamp ({@code 1$}) in
 114      *     a square bracket.
 115      *     <pre>
 116      *     WARNING: warning message [Tue Mar 22 13:11:31 PDT 2011]
 117      *     </pre></li>
 118      * <li> {@code java.util.logging.SimpleFormatter.format="%1$tc %2$s%n%4$s: %5$s%6$s%n"}
 119      *     <p>This prints 2 lines where the first line includes
 120      *     the timestamp ({@code 1$}) and the source ({@code 2$});
 121      *     the second line includes the log level ({@code 4$}) and
 122      *     the log message ({@code 5$}) followed by the throwable
 123      *     and its backtrace ({@code 6$}), if any:
 124      *     <pre>
 125      *     Tue Mar 22 13:11:31 PDT 2011 MyClass fatal
 126      *     SEVERE: several message with an exception
 127      *     java.lang.IllegalArgumentException: invalid argument
 128      *             at MyClass.mash(MyClass.java:9)
 129      *             at MyClass.crunch(MyClass.java:6)
 130      *             at MyClass.main(MyClass.java:3)
 131      *     </pre></li>
 132      * <li> {@code java.util.logging.SimpleFormatter.format="%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%n"}
 133      *      <p>This prints 2 lines similar to the example above
 134      *         with a different date/time formatting and does not print
 135      *         the throwable and its backtrace:
 136      *     <pre>
 137      *     Mar 22, 2011 1:11:31 PM MyClass fatal
 138      *     SEVERE: several message with an exception
 139      *     </pre></li>
 140      * <li> {@code java.util.logging.SimpleFormatter.format="%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS.%1$tN %1$Tp %2$s%n%4$s: %5$s%6$s%n"}
 141      *      <p>Since JDK 9, {@code java.util.logging} uses {@link
 142      *         java.time.Clock#systemUTC() java.time} to create more precise time
 143      *         stamps.
 144      *         The format above can be used to add a {@code .%1$tN} to the
 145      *         date/time formatting so that nanoseconds will also be printed:
 146      *     <pre>
 147      *     Feb 06, 2015 5:33:10.279216000 PM example.Main main
 148      *     INFO: This is a test
 149      *     </pre></li>
 150      * </ul>
 151      * <p>This method can also be overridden in a subclass.
 152      * It is recommended to use the {@link Formatter#formatMessage}
 153      * convenience method to localize and format the message field.
 154      *
 155      * @param record the log record to be formatted.
 156      * @return a formatted log record
 157      */
 158     @Override
 159     public String format(LogRecord record) {
 160         ZonedDateTime zdt = ZonedDateTime.ofInstant(
 161                 record.getInstant(), ZoneId.systemDefault());
 162         String source;
 163         if (record.getSourceClassName() != null) {
 164             source = record.getSourceClassName();
 165             if (record.getSourceMethodName() != null) {
 166                source += " " + record.getSourceMethodName();
 167             }
 168         } else {
 169             source = record.getLoggerName();
 170         }
 171         String message = formatMessage(record);
 172         String throwable = "";
 173         if (record.getThrown() != null) {
 174             StringWriter sw = new StringWriter();
 175             PrintWriter pw = new PrintWriter(sw);
 176             pw.println();
 177             record.getThrown().printStackTrace(pw);
 178             pw.close();
 179             throwable = sw.toString();
 180         }
 181         return String.format(format,
 182                              zdt,
 183                              source,
 184                              record.getLoggerName(),
 185                              record.getLevel().getLocalizedLevelName(),
 186                              message,
 187                              throwable);
 188     }
 189 }