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