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     public String toSerializable(final LogEvent event) {
101         final StringBuilder buf = new StringBuilder(DEFAULT_SIZE);
102 
103         // We yield to the \r\n heresy.
104 
105         buf.append("<log4j:event logger=\"");
106         String name = event.getLoggerName();
107         if (name.length() == 0) {
108             name = "root";
109         }
110         buf.append(Transform.escapeTags(name));
111         buf.append("\" timestamp=\"");
112         buf.append(event.getMillis());
113         buf.append("\" level=\"");
114         buf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
115         buf.append("\" thread=\"");
116         buf.append(Transform.escapeTags(event.getThreadName()));
117         buf.append("\">\r\n");
118 
119         final Message msg = event.getMessage();
120         if (msg != null) {
121             boolean xmlSupported = false;
122             if (msg instanceof MultiformatMessage) {
123                 final String[] formats = ((MultiformatMessage) msg).getFormats();
124                 for (final String format : formats) {
125                     if (format.equalsIgnoreCase("XML")) {
126                         xmlSupported = true;
127                     }
128                 }
129             }
130             if (xmlSupported) {
131                 buf.append("<log4j:message>");
132                 buf.append(((MultiformatMessage) msg).getFormattedMessage(FORMATS));
133                 buf.append("</log4j:message>");
134             } else {
135                 buf.append("<log4j:message><![CDATA[");
136                 // Append the rendered message. Also make sure to escape any
137                 // existing CDATA sections.
138                 Transform.appendEscapingCDATA(buf, event.getMessage().getFormattedMessage());
139                 buf.append("]]></log4j:message>\r\n");
140             }
141         }
142 
143         if (event.getContextStack().getDepth() > 0) {
144             buf.append("<log4j:NDC><![CDATA[");
145             Transform.appendEscapingCDATA(buf, event.getContextStack().toString());
146             buf.append("]]></log4j:NDC>\r\n");
147         }
148 
149         final Throwable throwable = event.getThrown();
150         if (throwable != null) {
151             final List<String> s = getThrowableString(throwable);
152             buf.append("<log4j:throwable><![CDATA[");
153             for (final String str : s) {
154                 Transform.appendEscapingCDATA(buf, str);
155                 buf.append("\r\n");
156             }
157             buf.append("]]></log4j:throwable>\r\n");
158         }
159 
160         if (locationInfo) {
161             final StackTraceElement element = event.getSource();
162             buf.append("<log4j:locationInfo class=\"");
163             buf.append(Transform.escapeTags(element.getClassName()));
164             buf.append("\" method=\"");
165             buf.append(Transform.escapeTags(element.getMethodName()));
166             buf.append("\" file=\"");
167             buf.append(Transform.escapeTags(element.getFileName()));
168             buf.append("\" line=\"");
169             buf.append(element.getLineNumber());
170             buf.append("\"/>\r\n");
171         }
172 
173         if (properties && event.getContextMap().size() > 0) {
174             buf.append("<log4j:properties>\r\n");
175             for (final Map.Entry<String, String> entry : event.getContextMap().entrySet()) {
176                 buf.append("<log4j:data name=\"");
177                 buf.append(Transform.escapeTags(entry.getKey()));
178                 buf.append("\" value=\"");
179                 buf.append(Transform.escapeTags(String.valueOf(entry.getValue())));
180                 buf.append("\"/>\r\n");
181             }
182             buf.append("</log4j:properties>\r\n");
183         }
184 
185         buf.append("</log4j:event>\r\n\r\n");
186 
187         return buf.toString();
188     }
189 
190     /**
191      * Returns appropriate XML headers.
192      * @return a byte array containing the header.
193      */
194     @Override
195     public byte[] getHeader() {
196         if (!complete) {
197             return null;
198         }
199         final StringBuilder sbuf = new StringBuilder();
200         sbuf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
201         sbuf.append("<log4j:eventSet xmlns:log4j=\"http://logging.apache.org/log4j/\">\r\n");
202         return sbuf.toString().getBytes(getCharset());
203     }
204 
205 
206     /**
207      * Returns appropriate XML headers.
208      * @return a byte array containing the footer.
209      */
210     @Override
211     public byte[] getFooter() {
212         if (!complete) {
213             return null;
214         }
215         final StringBuilder sbuf = new StringBuilder();
216         sbuf.append("</log4j:eventSet>\r\n");
217         return sbuf.toString().getBytes(getCharset());
218     }
219 
220     /**
221      * XMLLayout's content format is specified by:<p/>
222      * Key: "dtd" Value: "log4j.dtd"<p/>
223      * Key: "version" Value: "1.2"
224      * @return Map of content format keys supporting XMLLayout
225      */
226     public Map<String, String> getContentFormat() {
227         Map<String, String> result = new HashMap<String, String>();
228         result.put("dtd", "log4j.dtd");
229         result.put("version", "1.2");
230         return result;
231     }
232 
233     @Override
234     /**
235      * @return The content type.
236      */
237     public String getContentType() {
238         return "text/xml";
239     }
240 
241     List<String> getThrowableString(final Throwable throwable) {
242         final StringWriter sw = new StringWriter();
243         final PrintWriter pw = new PrintWriter(sw);
244         try {
245             throwable.printStackTrace(pw);
246         } catch (final RuntimeException ex) {
247             // Ignore any exceptions.
248         }
249         pw.flush();
250         final LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
251         final ArrayList<String> lines = new ArrayList<String>();
252         try {
253           String line = reader.readLine();
254           while (line != null) {
255             lines.add(line);
256             line = reader.readLine();
257           }
258         } catch (final IOException ex) {
259             if (ex instanceof InterruptedIOException) {
260                 Thread.currentThread().interrupt();
261             }
262             lines.add(ex.toString());
263         }
264         return lines;
265     }
266 
267     /**
268      * Create an XML Layout.
269      * @param locationInfo If "true" include the location information in the generated XML.
270      * @param properties If "true" include the thread context in the generated XML.
271      * @param complete If "true" include the XML header.
272      * @param charsetName The character set to use.
273      * @return An XML Layout.
274      */
275     @PluginFactory
276     public static XMLLayout createLayout(@PluginAttr("locationInfo") final String locationInfo,
277                                          @PluginAttr("properties") final String properties,
278                                          @PluginAttr("complete") final String complete,
279                                          @PluginAttr("charset") final String charsetName) {
280         final Charset charset = Charsets.getSupportedCharset(charsetName);
281         final boolean info = locationInfo == null ? false : Boolean.valueOf(locationInfo);
282         final boolean props = properties == null ? false : Boolean.valueOf(properties);
283         final boolean comp = complete == null ? false : Boolean.valueOf(complete);
284         return new XMLLayout(info, props, comp, charset);
285     }
286 }