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