View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.layout;
18  
19  import java.nio.charset.Charset;
20  import java.nio.charset.StandardCharsets;
21  import java.util.HashMap;
22  import java.util.Map;
23  
24  import org.apache.logging.log4j.core.Layout;
25  import org.apache.logging.log4j.core.config.Configuration;
26  import org.apache.logging.log4j.core.config.Node;
27  import org.apache.logging.log4j.core.config.plugins.Plugin;
28  import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
29  import org.apache.logging.log4j.core.jackson.XmlConstants;
30  import org.apache.logging.log4j.core.util.KeyValuePair;
31  
32  /**
33   * Appends a series of {@code event} elements as defined in the <a href="log4j.dtd">log4j.dtd</a>.
34   *
35   * <h3>Complete well-formed XML vs. fragment XML</h3>
36   * <p>
37   * If you configure {@code complete="true"}, the appender outputs a well-formed XML document where the default namespace
38   * is the log4j namespace {@value XmlConstants#XML_NAMESPACE}. By default, with {@code complete="false"}, you should
39   * include the output as an <em>external entity</em> in a separate file to form a well-formed XML document.
40   * </p>
41   * <p>
42   * If {@code complete="false"}, the appender does not write the XML processing instruction and the root element.
43   * </p>
44   * <h3>Encoding</h3>
45   * <p>
46   * Appenders using this layout should have their {@code charset} set to {@code UTF-8} or {@code UTF-16}, otherwise
47   * events containing non-ASCII characters could result in corrupted log files.
48   * </p>
49   * <h3>Pretty vs. compact XML</h3>
50   * <p>
51   * By default, the XML layout is not compact (compact = not "pretty") with {@code compact="false"}, which means the
52   * appender uses end-of-line characters and indents lines to format the XML. If {@code compact="true"}, then no
53   * end-of-line or indentation is used. Message content may contain, of course, end-of-lines.
54   * </p>
55   * <h3>Additional Fields</h3>
56   * <p>
57   * This property allows addition of custom fields into generated JSON.
58   * {@code <XmlLayout><KeyValuePair key="foo" value="bar"/></XmlLayout>} inserts {@code <foo>bar</foo>} directly
59   * into XML output. Supports Lookup expressions.
60   * </p>
61   */
62  @Plugin(name = "XmlLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
63  public final class XmlLayout extends AbstractJacksonLayout {
64  
65      private static final String ROOT_TAG = "Events";
66  
67      public static class Builder<B extends Builder<B>> extends AbstractJacksonLayout.Builder<B>
68          implements org.apache.logging.log4j.core.util.Builder<XmlLayout> {
69  
70          public Builder() {
71              super();
72              setCharset(StandardCharsets.UTF_8);
73          }
74  
75          @Override
76          public XmlLayout build() {
77              return new XmlLayout(getConfiguration(), isLocationInfo(), isProperties(), isComplete(),
78                      isCompact(), getEndOfLine(), getCharset(), isIncludeStacktrace(), isStacktraceAsString(),
79                      isIncludeNullDelimiter(), getAdditionalFields());
80          }
81      }
82  
83      /**
84       * @deprecated Use {@link #newBuilder()} instead
85       */
86      @Deprecated
87      protected XmlLayout(final boolean locationInfo, final boolean properties, final boolean complete,
88                          final boolean compact, final Charset charset, final boolean includeStacktrace) {
89          this(null, locationInfo, properties, complete, compact, null, charset, includeStacktrace, false, false, null);
90      }
91  
92      private XmlLayout(final Configuration config, final boolean locationInfo, final boolean properties,
93                        final boolean complete, final boolean compact, final String endOfLine, final Charset charset,
94                        final boolean includeStacktrace, final boolean stacktraceAsString,
95                        final boolean includeNullDelimiter,
96                        final KeyValuePair[] additionalFields) {
97          super(config, new JacksonFactory.XML(includeStacktrace, stacktraceAsString).newWriter(
98              locationInfo, properties, compact),
99              charset, compact, complete, false, endOfLine, null, null, includeNullDelimiter,
100             additionalFields);
101     }
102 
103     /**
104      * Returns appropriate XML headers.
105      * <ol>
106      * <li>XML processing instruction</li>
107      * <li>XML root element</li>
108      * </ol>
109      *
110      * @return a byte array containing the header.
111      */
112     @Override
113     public byte[] getHeader() {
114         if (!complete) {
115             return null;
116         }
117         final StringBuilder buf = new StringBuilder();
118         buf.append("<?xml version=\"1.0\" encoding=\"");
119         buf.append(this.getCharset().name());
120         buf.append("\"?>");
121         buf.append(this.eol);
122         // Make the log4j namespace the default namespace, no need to use more space with a namespace prefix.
123         buf.append('<');
124         buf.append(ROOT_TAG);
125         buf.append(" xmlns=\"" + XmlConstants.XML_NAMESPACE + "\">");
126         buf.append(this.eol);
127         return buf.toString().getBytes(this.getCharset());
128     }
129 
130     /**
131      * Returns appropriate XML footer.
132      *
133      * @return a byte array containing the footer, closing the XML root element.
134      */
135     @Override
136     public byte[] getFooter() {
137         if (!complete) {
138             return null;
139         }
140         return getBytes("</" + ROOT_TAG + '>' + this.eol);
141     }
142 
143     /**
144      * Gets this XmlLayout's content format. Specified by:
145      * <ul>
146      * <li>Key: "dtd" Value: "log4j-events.dtd"</li>
147      * <li>Key: "version" Value: "2.0"</li>
148      * </ul>
149      *
150      * @return Map of content format keys supporting XmlLayout
151      */
152     @Override
153     public Map<String, String> getContentFormat() {
154         final Map<String, String> result = new HashMap<>();
155         // result.put("dtd", "log4j-events.dtd");
156         result.put("xsd", "log4j-events.xsd");
157         result.put("version", "2.0");
158         return result;
159     }
160 
161     /**
162      * @return The content type.
163      */
164     @Override
165     public String getContentType() {
166         return "text/xml; charset=" + this.getCharset();
167     }
168 
169     /**
170      * Creates an XML Layout.
171      *
172      * @param locationInfo If "true", includes the location information in the generated XML.
173      * @param properties If "true", includes the thread context map in the generated XML.
174      * @param complete If "true", includes the XML header and footer, defaults to "false".
175      * @param compact If "true", does not use end-of-lines and indentation, defaults to "false".
176      * @param charset The character set to use, if {@code null}, uses "UTF-8".
177      * @param includeStacktrace
178      *            If "true", includes the stacktrace of any Throwable in the generated XML, defaults to "true".
179      * @return An XML Layout.
180      *
181      * @deprecated Use {@link #newBuilder()} instead
182      */
183     @Deprecated
184     public static XmlLayout createLayout(
185             final boolean locationInfo,
186             final boolean properties,
187             final boolean complete,
188             final boolean compact,
189             final Charset charset,
190             final boolean includeStacktrace) {
191         return new XmlLayout(null, locationInfo, properties, complete, compact, null, charset, includeStacktrace, false,
192                 false, null);
193     }
194 
195     @PluginBuilderFactory
196     public static <B extends Builder<B>> B newBuilder() {
197         return new Builder<B>().asBuilder();
198     }
199 
200     /**
201      * Creates an XML Layout using the default settings.
202      *
203      * @return an XML Layout.
204      */
205     public static XmlLayout createDefaultLayout() {
206         return new XmlLayout(null, false, false, false, false, null, StandardCharsets.UTF_8, true, false, false, null);
207     }
208 }