Path: blob/master/src/java.logging/share/classes/java/util/logging/SimpleFormatter.java
41159 views
/*1* Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/242526package java.util.logging;2728import java.io.*;29import java.time.ZoneId;30import java.time.ZonedDateTime;31import jdk.internal.logger.SurrogateLogger;3233/**34* Print a brief summary of the {@code LogRecord} in a human readable35* format. The summary will typically be 1 or 2 lines.36*37* <p>38* <a id="formatting">39* <b>Configuration:</b></a>40* The {@code SimpleFormatter} is initialized with the format string41* specified in the {@systemProperty java.util.logging.SimpleFormatter.format}42* property to {@linkplain #format(LogRecord) format} the log messages.43* This property can be defined44* in the {@linkplain LogManager#getProperty logging properties}45* configuration file46* or as a system property. If this property is set in both47* the logging properties and system properties,48* the format string specified in the system property will be used.49* If this property is not defined or the given format string50* is {@linkplain java.util.IllegalFormatException illegal},51* the default format is implementation-specific.52*53* @since 1.454* @see java.util.Formatter55*/5657public class SimpleFormatter extends Formatter {5859// format string for printing the log record60static String getLoggingProperty(String name) {61return LogManager.getLogManager().getProperty(name);62}6364private final String format =65SurrogateLogger.getSimpleFormat(SimpleFormatter::getLoggingProperty);6667/**68* Create a {@code SimpleFormatter}.69*/70public SimpleFormatter() {}7172/**73* Format the given LogRecord.74* <p>75* The formatting can be customized by specifying the format string76* in the <a href="#formatting">77* {@code java.util.logging.SimpleFormatter.format}</a> property.78* The given {@code LogRecord} will be formatted as if by calling:79* <pre>80* {@link String#format String.format}(format, date, source, logger, level, message, thrown);81* </pre>82* where the arguments are:<br>83* <ol>84* <li>{@code format} - the {@link java.util.Formatter85* java.util.Formatter} format string specified in the86* {@code java.util.logging.SimpleFormatter.format} property87* or the default format.</li>88* <li>{@code date} - a {@link ZonedDateTime} object representing89* {@linkplain LogRecord#getInstant() event time} of the log record90* in the {@link ZoneId#systemDefault()} system time zone.</li>91* <li>{@code source} - a string representing the caller, if available;92* otherwise, the logger's name.</li>93* <li>{@code logger} - the logger's name.</li>94* <li>{@code level} - the {@linkplain Level#getLocalizedName95* log level}.</li>96* <li>{@code message} - the formatted log message97* returned from the {@link Formatter#formatMessage(LogRecord)}98* method. It uses {@link java.text.MessageFormat java.text}99* formatting and does not use the {@code java.util.Formatter100* format} argument.</li>101* <li>{@code thrown} - a string representing102* the {@linkplain LogRecord#getThrown throwable}103* associated with the log record and its backtrace104* beginning with a newline character, if any;105* otherwise, an empty string.</li>106* </ol>107*108* <p>Some example formats:<br>109* <ul>110* <li> {@code java.util.logging.SimpleFormatter.format="%4$s: %5$s [%1$tc]%n"}111* <p>This prints 1 line with the log level ({@code 4$}),112* the log message ({@code 5$}) and the timestamp ({@code 1$}) in113* a square bracket.114* <pre>115* WARNING: warning message [Tue Mar 22 13:11:31 PDT 2011]116* </pre></li>117* <li> {@code java.util.logging.SimpleFormatter.format="%1$tc %2$s%n%4$s: %5$s%6$s%n"}118* <p>This prints 2 lines where the first line includes119* the timestamp ({@code 1$}) and the source ({@code 2$});120* the second line includes the log level ({@code 4$}) and121* the log message ({@code 5$}) followed by the throwable122* and its backtrace ({@code 6$}), if any:123* <pre>124* Tue Mar 22 13:11:31 PDT 2011 MyClass fatal125* SEVERE: several message with an exception126* java.lang.IllegalArgumentException: invalid argument127* at MyClass.mash(MyClass.java:9)128* at MyClass.crunch(MyClass.java:6)129* at MyClass.main(MyClass.java:3)130* </pre></li>131* <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"}132* <p>This prints 2 lines similar to the example above133* with a different date/time formatting and does not print134* the throwable and its backtrace:135* <pre>136* Mar 22, 2011 1:11:31 PM MyClass fatal137* SEVERE: several message with an exception138* </pre></li>139* <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"}140* <p>Since JDK 9, {@code java.util.logging} uses {@link141* java.time.Clock#systemUTC() java.time} to create more precise time142* stamps.143* The format above can be used to add a {@code .%1$tN} to the144* date/time formatting so that nanoseconds will also be printed:145* <pre>146* Feb 06, 2015 5:33:10.279216000 PM example.Main main147* INFO: This is a test148* </pre></li>149* </ul>150* <p>This method can also be overridden in a subclass.151* It is recommended to use the {@link Formatter#formatMessage}152* convenience method to localize and format the message field.153*154* @param record the log record to be formatted.155* @return a formatted log record156*/157@Override158public String format(LogRecord record) {159ZonedDateTime zdt = ZonedDateTime.ofInstant(160record.getInstant(), ZoneId.systemDefault());161String source;162if (record.getSourceClassName() != null) {163source = record.getSourceClassName();164if (record.getSourceMethodName() != null) {165source += " " + record.getSourceMethodName();166}167} else {168source = record.getLoggerName();169}170String message = formatMessage(record);171String throwable = "";172if (record.getThrown() != null) {173StringWriter sw = new StringWriter();174PrintWriter pw = new PrintWriter(sw);175pw.println();176record.getThrown().printStackTrace(pw);177pw.close();178throwable = sw.toString();179}180return String.format(format,181zdt,182source,183record.getLoggerName(),184record.getLevel().getLocalizedLevelName(),185message,186throwable);187}188}189190191