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.List;
028    import java.util.Map;
029    
030    import org.apache.logging.log4j.core.config.plugins.Plugin;
031    import org.apache.logging.log4j.core.config.plugins.PluginAttr;
032    import org.apache.logging.log4j.core.config.plugins.PluginFactory;
033    import org.apache.logging.log4j.core.helpers.Charsets;
034    import org.apache.logging.log4j.core.helpers.Transform;
035    import org.apache.logging.log4j.core.LogEvent;
036    import org.apache.logging.log4j.message.Message;
037    import org.apache.logging.log4j.message.MultiformatMessage;
038    
039    
040    /**
041     * The output of the XMLLayout consists of a series of log4j:event
042     * elements as defined in the <a href="log4j.dtd">log4j.dtd</a>. If configured to do so it will
043     * output a complete well-formed XML file. The output is designed to be
044     * included as an <em>external entity</em> in a separate file to form
045     * a correct XML file.
046     * <p/>
047     * <p>For example, if <code>abc</code> is the name of the file where
048     * the XMLLayout ouput goes, then a well-formed XML file would be:
049     * <p/>
050     * <pre>
051     * &lt;?xml version="1.0" ?&gt;
052     *
053     * &lt;!DOCTYPE log4j:eventSet SYSTEM "log4j.dtd" [&lt;!ENTITY data SYSTEM "abc"&gt;]&gt;
054     *
055     * &lt;log4j:eventSet version="1.2" xmlns:log4j="http://logging.apache.org/log4j/"&gt;
056     * &nbsp;&nbsp;&data;
057     * &lt;/log4j:eventSet&gt;
058     * </pre>
059     * <p/>
060     * <p>This approach enforces the independence of the XMLLayout and the
061     * appender where it is embedded.
062     * <p/>
063     * <p>The <code>version</code> attribute helps components to correctly
064     * intrepret output generated by XMLLayout. The value of this
065     * attribute should be "1.1" for output generated by log4j versions
066     * prior to log4j 1.2 (final release) and "1.2" for relase 1.2 and
067     * later.
068     * <p/>
069     * Appenders using this layout should have their encoding
070     * set to UTF-8 or UTF-16, otherwise events containing
071     * non ASCII characters could result in corrupted
072     * log files.
073     */
074    @Plugin(name = "XMLLayout", type = "Core", elementType = "layout", printObject = true)
075    public class XMLLayout extends AbstractStringLayout {
076    
077        private static final int DEFAULT_SIZE = 256;
078    
079        private static final String[] FORMATS = new String[] {"xml"};
080    
081        private final boolean locationInfo;
082        private final boolean properties;
083        private final boolean complete;
084    
085        protected XMLLayout(final boolean locationInfo, final boolean properties, final boolean complete,
086                            final Charset charset) {
087            super(charset);
088            this.locationInfo = locationInfo;
089            this.properties = properties;
090            this.complete = complete;
091        }
092    
093        /**
094         * Formats a {@link org.apache.logging.log4j.core.LogEvent} in conformance with the log4j.dtd.
095         *
096         * @param event The LogEvent.
097         * @return The XML representation of the LogEvent.
098         */
099        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    }