001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements. See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache license, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License. You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the license for the specific language governing permissions and
015     * limitations under the license.
016     */
017    package org.apache.logging.log4j.core.layout;
018    
019    import java.io.IOException;
020    import java.io.InterruptedIOException;
021    import java.io.LineNumberReader;
022    import java.io.PrintWriter;
023    import java.io.StringReader;
024    import java.io.StringWriter;
025    import java.nio.charset.Charset;
026    import java.util.ArrayList;
027    import java.util.HashMap;
028    import java.util.List;
029    import java.util.Map;
030    
031    import org.apache.logging.log4j.core.config.plugins.Plugin;
032    import org.apache.logging.log4j.core.config.plugins.PluginAttr;
033    import org.apache.logging.log4j.core.config.plugins.PluginFactory;
034    import org.apache.logging.log4j.core.helpers.Charsets;
035    import org.apache.logging.log4j.core.helpers.Transform;
036    import org.apache.logging.log4j.core.LogEvent;
037    import org.apache.logging.log4j.message.Message;
038    import org.apache.logging.log4j.message.MultiformatMessage;
039    
040    
041    /**
042     * The output of the XMLLayout consists of a series of log4j:event
043     * elements as defined in the <a href="log4j.dtd">log4j.dtd</a>. If configured to do so it will
044     * output a complete well-formed XML file. The output is designed to be
045     * included as an <em>external entity</em> in a separate file to form
046     * a correct XML file.
047     * <p/>
048     * <p>For example, if <code>abc</code> is the name of the file where
049     * the XMLLayout ouput goes, then a well-formed XML file would be:
050     * <p/>
051     * <pre>
052     * &lt;?xml version="1.0" ?&gt;
053     *
054     * &lt;!DOCTYPE log4j:eventSet SYSTEM "log4j.dtd" [&lt;!ENTITY data SYSTEM "abc"&gt;]&gt;
055     *
056     * &lt;log4j:eventSet version="1.2" xmlns:log4j="http://logging.apache.org/log4j/"&gt;
057     * &nbsp;&nbsp;&data;
058     * &lt;/log4j:eventSet&gt;
059     * </pre>
060     * <p/>
061     * <p>This approach enforces the independence of the XMLLayout and the
062     * appender where it is embedded.
063     * <p/>
064     * <p>The <code>version</code> attribute helps components to correctly
065     * interpret output generated by XMLLayout. The value of this
066     * attribute should be "1.1" for output generated by log4j versions
067     * prior to log4j 1.2 (final release) and "1.2" for release 1.2 and
068     * later.
069     * <p/>
070     * Appenders using this layout should have their encoding
071     * set to UTF-8 or UTF-16, otherwise events containing
072     * non ASCII characters could result in corrupted
073     * log files.
074     */
075    @Plugin(name = "XMLLayout", category = "Core", elementType = "layout", printObject = true)
076    public class XMLLayout extends AbstractStringLayout {
077    
078        private static final int DEFAULT_SIZE = 256;
079    
080        private static final String[] FORMATS = new String[] {"xml"};
081    
082        private final boolean locationInfo;
083        private final boolean properties;
084        private final boolean complete;
085    
086        protected XMLLayout(final boolean locationInfo, final boolean properties, final boolean complete,
087                            final Charset charset) {
088            super(charset);
089            this.locationInfo = locationInfo;
090            this.properties = properties;
091            this.complete = complete;
092        }
093    
094        /**
095         * Formats a {@link org.apache.logging.log4j.core.LogEvent} in conformance with the log4j.dtd.
096         *
097         * @param event The LogEvent.
098         * @return The XML representation of the LogEvent.
099         */
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    }