Path: blob/master/src/java.logging/share/classes/java/util/logging/XMLFormatter.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.nio.charset.Charset;29import java.time.Instant;30import java.time.format.DateTimeFormatter;31import java.util.*;3233/**34* Format a LogRecord into a standard XML format.35* <p>36* The DTD specification is provided as Appendix A to the37* Java Logging APIs specification.38* <p>39* The XMLFormatter can be used with arbitrary character encodings,40* but it is recommended that it normally be used with UTF-8. The41* character encoding can be set on the output Handler.42*43* @implSpec Since JDK 9, instances of {@linkplain LogRecord} contain44* an {@link LogRecord#getInstant() Instant} which can have nanoseconds below45* the millisecond resolution.46* The DTD specification has been updated to allow for an optional47* {@code <nanos>} element. By default, the XMLFormatter will compute the48* nanosecond adjustment below the millisecond resolution (using49* {@code LogRecord.getInstant().getNano() % 1000_000}) - and if this is not 0,50* this adjustment value will be printed in the new {@code <nanos>} element.51* The event instant can then be reconstructed using52* {@code Instant.ofEpochSecond(millis/1000L, (millis % 1000L) * 1000_000L + nanos)}53* where {@code millis} and {@code nanos} represent the numbers serialized in54* the {@code <millis>} and {@code <nanos>} elements, respectively.55* <br>56* The {@code <date>} element will now contain the whole instant as formatted57* by the {@link DateTimeFormatter#ISO_INSTANT DateTimeFormatter.ISO_INSTANT}58* formatter.59* <p>60* For compatibility with old parsers, XMLFormatters can61* be configured to revert to the old format by specifying a62* {@code <xml-formatter-fully-qualified-class-name>.useInstant = false}63* {@linkplain LogManager#getProperty(java.lang.String) property} in the64* logging configuration. When {@code useInstant} is {@code false}, the old65* formatting will be preserved. When {@code useInstant} is {@code true}66* (the default), the {@code <nanos>} element will be printed and the67* {@code <date>} element will contain the {@linkplain68* DateTimeFormatter#ISO_INSTANT formatted} instant.69* <p>70* For instance, in order to configure plain instances of XMLFormatter to omit71* the new {@code <nano>} element,72* {@code java.util.logging.XMLFormatter.useInstant = false} can be specified73* in the logging configuration.74*75* @since 1.476*/7778public class XMLFormatter extends Formatter {79private final LogManager manager = LogManager.getLogManager();80private final boolean useInstant;8182/**83* Creates a new instance of XMLFormatter.84*85* @implSpec86* Since JDK 9, the XMLFormatter will print out the record {@linkplain87* LogRecord#getInstant() event time} as an Instant. This instant88* has the best resolution available on the system. The {@code <date>}89* element will contain the instant as formatted by the {@link90* DateTimeFormatter#ISO_INSTANT}.91* In addition, an optional {@code <nanos>} element containing a92* nanosecond adjustment will be printed if the instant contains some93* nanoseconds below the millisecond resolution.94* <p>95* This new behavior can be turned off, and the old formatting restored,96* by specifying a property in the {@linkplain97* LogManager#getProperty(java.lang.String) logging configuration}.98* If {@code LogManager.getLogManager().getProperty(99* this.getClass().getName()+".useInstant")} is {@code "false"} or100* {@code "0"}, the old formatting will be restored.101*/102public XMLFormatter() {103useInstant = (manager == null)104|| manager.getBooleanProperty(105this.getClass().getName()+".useInstant", true);106}107108// Append a two digit number.109private void a2(StringBuilder sb, int x) {110if (x < 10) {111sb.append('0');112}113sb.append(x);114}115116// Append the time and date in ISO 8601 format117private void appendISO8601(StringBuilder sb, long millis) {118GregorianCalendar cal = new GregorianCalendar();119cal.setTimeInMillis(millis);120sb.append(cal.get(Calendar.YEAR));121sb.append('-');122a2(sb, cal.get(Calendar.MONTH) + 1);123sb.append('-');124a2(sb, cal.get(Calendar.DAY_OF_MONTH));125sb.append('T');126a2(sb, cal.get(Calendar.HOUR_OF_DAY));127sb.append(':');128a2(sb, cal.get(Calendar.MINUTE));129sb.append(':');130a2(sb, cal.get(Calendar.SECOND));131}132133// Append to the given StringBuilder an escaped version of the134// given text string where XML special characters have been escaped.135// For a null string we append "<null>"136private void escape(StringBuilder sb, String text) {137if (text == null) {138text = "<null>";139}140for (int i = 0; i < text.length(); i++) {141char ch = text.charAt(i);142if (ch == '<') {143sb.append("<");144} else if (ch == '>') {145sb.append(">");146} else if (ch == '&') {147sb.append("&");148} else {149sb.append(ch);150}151}152}153154/**155* Format the given message to XML.156* <p>157* This method can be overridden in a subclass.158* It is recommended to use the {@link Formatter#formatMessage}159* convenience method to localize and format the message field.160*161* @param record the log record to be formatted.162* @return a formatted log record163*/164@Override165public String format(LogRecord record) {166StringBuilder sb = new StringBuilder(500);167sb.append("<record>\n");168169final Instant instant = record.getInstant();170171sb.append(" <date>");172if (useInstant) {173// If useInstant is true - we will print the instant in the174// date field, using the ISO_INSTANT formatter.175DateTimeFormatter.ISO_INSTANT.formatTo(instant, sb);176} else {177// If useInstant is false - we will keep the 'old' formating178appendISO8601(sb, instant.toEpochMilli());179}180sb.append("</date>\n");181182sb.append(" <millis>");183sb.append(instant.toEpochMilli());184sb.append("</millis>\n");185186final int nanoAdjustment = instant.getNano() % 1000_000;187if (useInstant && nanoAdjustment != 0) {188sb.append(" <nanos>");189sb.append(nanoAdjustment);190sb.append("</nanos>\n");191}192193sb.append(" <sequence>");194sb.append(record.getSequenceNumber());195sb.append("</sequence>\n");196197String name = record.getLoggerName();198if (name != null) {199sb.append(" <logger>");200escape(sb, name);201sb.append("</logger>\n");202}203204sb.append(" <level>");205escape(sb, record.getLevel().toString());206sb.append("</level>\n");207208if (record.getSourceClassName() != null) {209sb.append(" <class>");210escape(sb, record.getSourceClassName());211sb.append("</class>\n");212}213214if (record.getSourceMethodName() != null) {215sb.append(" <method>");216escape(sb, record.getSourceMethodName());217sb.append("</method>\n");218}219220sb.append(" <thread>");221sb.append(record.getLongThreadID());222sb.append("</thread>\n");223224if (record.getMessage() != null) {225// Format the message string and its accompanying parameters.226String message = formatMessage(record);227sb.append(" <message>");228escape(sb, message);229sb.append("</message>");230sb.append("\n");231}232233// If the message is being localized, output the key, resource234// bundle name, and params.235ResourceBundle bundle = record.getResourceBundle();236try {237if (bundle != null && bundle.getString(record.getMessage()) != null) {238sb.append(" <key>");239escape(sb, record.getMessage());240sb.append("</key>\n");241sb.append(" <catalog>");242escape(sb, record.getResourceBundleName());243sb.append("</catalog>\n");244}245} catch (Exception ex) {246// The message is not in the catalog. Drop through.247}248249Object parameters[] = record.getParameters();250// Check to see if the parameter was not a messagetext format251// or was not null or empty252if (parameters != null && parameters.length != 0253&& record.getMessage().indexOf('{') == -1 ) {254for (Object parameter : parameters) {255sb.append(" <param>");256try {257escape(sb, parameter.toString());258} catch (Exception ex) {259sb.append("???");260}261sb.append("</param>\n");262}263}264265if (record.getThrown() != null) {266// Report on the state of the throwable.267Throwable th = record.getThrown();268sb.append(" <exception>\n");269sb.append(" <message>");270escape(sb, th.toString());271sb.append("</message>\n");272StackTraceElement trace[] = th.getStackTrace();273for (StackTraceElement frame : trace) {274sb.append(" <frame>\n");275sb.append(" <class>");276escape(sb, frame.getClassName());277sb.append("</class>\n");278sb.append(" <method>");279escape(sb, frame.getMethodName());280sb.append("</method>\n");281// Check for a line number.282if (frame.getLineNumber() >= 0) {283sb.append(" <line>");284sb.append(frame.getLineNumber());285sb.append("</line>\n");286}287sb.append(" </frame>\n");288}289sb.append(" </exception>\n");290}291292sb.append("</record>\n");293return sb.toString();294}295296/**297* Return the header string for a set of XML formatted records.298*299* @param h The target handler (can be null)300* @return a valid XML string301*/302@Override303public String getHead(Handler h) {304StringBuilder sb = new StringBuilder();305String encoding;306sb.append("<?xml version=\"1.0\"");307308if (h != null) {309encoding = h.getEncoding();310} else {311encoding = null;312}313314if (encoding == null) {315// Figure out the default encoding.316encoding = java.nio.charset.Charset.defaultCharset().name();317}318// Try to map the encoding name to a canonical name.319try {320Charset cs = Charset.forName(encoding);321encoding = cs.name();322} catch (Exception ex) {323// We hit problems finding a canonical name.324// Just use the raw encoding name.325}326327sb.append(" encoding=\"");328sb.append(encoding);329sb.append("\"");330sb.append(" standalone=\"no\"?>\n");331332sb.append("<!DOCTYPE log SYSTEM \"logger.dtd\">\n");333sb.append("<log>\n");334return sb.toString();335}336337/**338* Return the tail string for a set of XML formatted records.339*340* @param h The target handler (can be null)341* @return a valid XML string342*/343@Override344public String getTail(Handler h) {345return "</log>\n";346}347}348349350