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