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.io.IOException;
20  import java.io.InterruptedIOException;
21  import java.io.LineNumberReader;
22  import java.io.PrintWriter;
23  import java.io.StringReader;
24  import java.io.StringWriter;
25  import java.nio.charset.Charset;
26  import java.util.ArrayList;
27  import java.util.HashMap;
28  import java.util.List;
29  import java.util.Map;
30  
31  import org.apache.logging.log4j.core.config.plugins.Plugin;
32  import org.apache.logging.log4j.core.config.plugins.PluginAttr;
33  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
34  import org.apache.logging.log4j.core.helpers.Charsets;
35  import org.apache.logging.log4j.core.helpers.Transform;
36  import org.apache.logging.log4j.core.LogEvent;
37  import org.apache.logging.log4j.message.Message;
38  import org.apache.logging.log4j.message.MultiformatMessage;
39  
40  
41  /**
42   * The output of the XMLLayout consists of a series of log4j:event
43   * elements as defined in the <a href="log4j.dtd">log4j.dtd</a>. If configured to do so it will
44   * output a complete well-formed XML file. The output is designed to be
45   * included as an <em>external entity</em> in a separate file to form
46   * a correct XML file.
47   * <p/>
48   * <p>For example, if <code>abc</code> is the name of the file where
49   * the XMLLayout ouput goes, then a well-formed XML file would be:
50   * <p/>
51   * <pre>
52   * &lt;?xml version="1.0" ?&gt;
53   *
54   * &lt;!DOCTYPE log4j:eventSet SYSTEM "log4j.dtd" [&lt;!ENTITY data SYSTEM "abc"&gt;]&gt;
55   *
56   * &lt;log4j:eventSet version="1.2" xmlns:log4j="http://logging.apache.org/log4j/"&gt;
57   * &nbsp;&nbsp;&data;
58   * &lt;/log4j:eventSet&gt;
59   * </pre>
60   * <p/>
61   * <p>This approach enforces the independence of the XMLLayout and the
62   * appender where it is embedded.
63   * <p/>
64   * <p>The <code>version</code> attribute helps components to correctly
65   * interpret output generated by XMLLayout. The value of this
66   * attribute should be "1.1" for output generated by log4j versions
67   * prior to log4j 1.2 (final release) and "1.2" for release 1.2 and
68   * later.
69   * <p/>
70   * Appenders using this layout should have their encoding
71   * set to UTF-8 or UTF-16, otherwise events containing
72   * non ASCII characters could result in corrupted
73   * log files.
74   */
75  @Plugin(name = "XMLLayout", category = "Core", elementType = "layout", printObject = true)
76  public class XMLLayout extends AbstractStringLayout {
77  
78      private static final int DEFAULT_SIZE = 256;
79  
80      private static final String[] FORMATS = new String[] {"xml"};
81  
82      private final boolean locationInfo;
83      private final boolean properties;
84      private final boolean complete;
85  
86      protected XMLLayout(final boolean locationInfo, final boolean properties, final boolean complete,
87                          final Charset charset) {
88          super(charset);
89          this.locationInfo = locationInfo;
90          this.properties = properties;
91          this.complete = complete;
92      }
93  
94      /**
95       * Formats a {@link org.apache.logging.log4j.core.LogEvent} in conformance with the log4j.dtd.
96       *
97       * @param event The LogEvent.
98       * @return The XML representation of the LogEvent.
99       */
100     @Override
101     public String toSerializable(final LogEvent event) {
102         final StringBuilder buf = new StringBuilder(DEFAULT_SIZE);
103 
104         // We yield to the \r\n heresy.
105 
106         buf.append("<log4j:event logger=\"");
107         String name = event.getLoggerName();
108         if (name.length() == 0) {
109             name = "root";
110         }
111         buf.append(Transform.escapeTags(name));
112         buf.append("\" timestamp=\"");
113         buf.append(event.getMillis());
114         buf.append("\" level=\"");
115         buf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
116         buf.append("\" thread=\"");
117         buf.append(Transform.escapeTags(event.getThreadName()));
118         buf.append("\">\r\n");
119 
120         final Message msg = event.getMessage();
121         if (msg != null) {
122             boolean xmlSupported = false;
123             if (msg instanceof MultiformatMessage) {
124                 final String[] formats = ((MultiformatMessage) msg).getFormats();
125                 for (final String format : formats) {
126                     if (format.equalsIgnoreCase("XML")) {
127                         xmlSupported = true;
128                     }
129                 }
130             }
131             if (xmlSupported) {
132                 buf.append("<log4j:message>");
133                 buf.append(((MultiformatMessage) msg).getFormattedMessage(FORMATS));
134                 buf.append("</log4j:message>");
135             } else {
136                 buf.append("<log4j:message><![CDATA[");
137                 // Append the rendered message. Also make sure to escape any
138                 // existing CDATA sections.
139                 Transform.appendEscapingCDATA(buf, event.getMessage().getFormattedMessage());
140                 buf.append("]]></log4j:message>\r\n");
141             }
142         }
143 
144         if (event.getContextStack().getDepth() > 0) {
145             buf.append("<log4j:NDC><![CDATA[");
146             Transform.appendEscapingCDATA(buf, event.getContextStack().toString());
147             buf.append("]]></log4j:NDC>\r\n");
148         }
149 
150         final Throwable throwable = event.getThrown();
151         if (throwable != null) {
152             final List<String> s = getThrowableString(throwable);
153             buf.append("<log4j:throwable><![CDATA[");
154             for (final String str : s) {
155                 Transform.appendEscapingCDATA(buf, str);
156                 buf.append("\r\n");
157             }
158             buf.append("]]></log4j:throwable>\r\n");
159         }
160 
161         if (locationInfo) {
162             final StackTraceElement element = event.getSource();
163             buf.append("<log4j:locationInfo class=\"");
164             buf.append(Transform.escapeTags(element.getClassName()));
165             buf.append("\" method=\"");
166             buf.append(Transform.escapeTags(element.getMethodName()));
167             buf.append("\" file=\"");
168             buf.append(Transform.escapeTags(element.getFileName()));
169             buf.append("\" line=\"");
170             buf.append(element.getLineNumber());
171             buf.append("\"/>\r\n");
172         }
173 
174         if (properties && event.getContextMap().size() > 0) {
175             buf.append("<log4j:properties>\r\n");
176             for (final Map.Entry<String, String> entry : event.getContextMap().entrySet()) {
177                 buf.append("<log4j:data name=\"");
178                 buf.append(Transform.escapeTags(entry.getKey()));
179                 buf.append("\" value=\"");
180                 buf.append(Transform.escapeTags(String.valueOf(entry.getValue())));
181                 buf.append("\"/>\r\n");
182             }
183             buf.append("</log4j:properties>\r\n");
184         }
185 
186         buf.append("</log4j:event>\r\n\r\n");
187 
188         return buf.toString();
189     }
190 
191     /**
192      * Returns appropriate XML headers.
193      * @return a byte array containing the header.
194      */
195     @Override
196     public byte[] getHeader() {
197         if (!complete) {
198             return null;
199         }
200         final StringBuilder sbuf = new StringBuilder();
201         sbuf.append("<?xml version=\"1.0\" encoding=\"");
202         sbuf.append(this.getCharset().name());
203         sbuf.append("\"?>\r\n");
204         sbuf.append("<log4j:eventSet xmlns:log4j=\"http://logging.apache.org/log4j/\">\r\n");
205         return sbuf.toString().getBytes(this.getCharset());
206     }
207 
208 
209     /**
210      * Returns appropriate XML headers.
211      * @return a byte array containing the footer.
212      */
213     @Override
214     public byte[] getFooter() {
215         if (!complete) {
216             return null;
217         }
218         final StringBuilder sbuf = new StringBuilder();
219         sbuf.append("</log4j:eventSet>\r\n");
220         return sbuf.toString().getBytes(getCharset());
221     }
222 
223     /**
224      * XMLLayout's content format is specified by:<p/>
225      * Key: "dtd" Value: "log4j.dtd"<p/>
226      * Key: "version" Value: "1.2"
227      * @return Map of content format keys supporting XMLLayout
228      */
229     @Override
230     public Map<String, String> getContentFormat() {
231         Map<String, String> result = new HashMap<String, String>();
232         result.put("dtd", "log4j.dtd");
233         result.put("version", "1.2");
234         return result;
235     }
236 
237     @Override
238     /**
239      * @return The content type.
240      */
241     public String getContentType() {
242         return "text/xml; charset=" + this.getCharset();
243     }
244 
245     List<String> getThrowableString(final Throwable throwable) {
246         final StringWriter sw = new StringWriter();
247         final PrintWriter pw = new PrintWriter(sw);
248         try {
249             throwable.printStackTrace(pw);
250         } catch (final RuntimeException ex) {
251             // Ignore any exceptions.
252         }
253         pw.flush();
254         final LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
255         final ArrayList<String> lines = new ArrayList<String>();
256         try {
257           String line = reader.readLine();
258           while (line != null) {
259             lines.add(line);
260             line = reader.readLine();
261           }
262         } catch (final IOException ex) {
263             if (ex instanceof InterruptedIOException) {
264                 Thread.currentThread().interrupt();
265             }
266             lines.add(ex.toString());
267         }
268         return lines;
269     }
270 
271     /**
272      * Creates an XML Layout.
273      * 
274      * @param locationInfo If "true" include the location information in the generated XML.
275      * @param properties If "true" include the thread context in the generated XML.
276      * @param complete If "true" include the XML header.
277      * @param charsetName The character set to use, if {@code null}, uses UTF-8.
278      * @return An XML Layout.
279      */
280     @PluginFactory
281     public static XMLLayout createLayout(@PluginAttr("locationInfo") final String locationInfo,
282                                          @PluginAttr("properties") final String properties,
283                                          @PluginAttr("complete") final String complete,
284                                          @PluginAttr("charset") final String charsetName) {
285         final Charset charset = Charsets.getSupportedCharset(charsetName, Charsets.UTF_8);
286         final boolean info = locationInfo == null ? false : Boolean.valueOf(locationInfo);
287         final boolean props = properties == null ? false : Boolean.valueOf(properties);
288         final boolean comp = complete == null ? false : Boolean.valueOf(complete);
289         return new XMLLayout(info, props, comp, charset);
290     }
291 }