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 * <?xml version="1.0" ?>
053 *
054 * <!DOCTYPE log4j:eventSet SYSTEM "log4j.dtd" [<!ENTITY data SYSTEM "abc">]>
055 *
056 * <log4j:eventSet version="1.2" xmlns:log4j="http://logging.apache.org/log4j/">
057 * &data;
058 * </log4j:eventSet>
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 public String toSerializable(final LogEvent event) {
101 final StringBuilder buf = new StringBuilder(DEFAULT_SIZE);
102
103 // We yield to the \r\n heresy.
104
105 buf.append("<log4j:event logger=\"");
106 String name = event.getLoggerName();
107 if (name.length() == 0) {
108 name = "root";
109 }
110 buf.append(Transform.escapeTags(name));
111 buf.append("\" timestamp=\"");
112 buf.append(event.getMillis());
113 buf.append("\" level=\"");
114 buf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
115 buf.append("\" thread=\"");
116 buf.append(Transform.escapeTags(event.getThreadName()));
117 buf.append("\">\r\n");
118
119 final Message msg = event.getMessage();
120 if (msg != null) {
121 boolean xmlSupported = false;
122 if (msg instanceof MultiformatMessage) {
123 final String[] formats = ((MultiformatMessage) msg).getFormats();
124 for (final String format : formats) {
125 if (format.equalsIgnoreCase("XML")) {
126 xmlSupported = true;
127 }
128 }
129 }
130 if (xmlSupported) {
131 buf.append("<log4j:message>");
132 buf.append(((MultiformatMessage) msg).getFormattedMessage(FORMATS));
133 buf.append("</log4j:message>");
134 } else {
135 buf.append("<log4j:message><![CDATA[");
136 // Append the rendered message. Also make sure to escape any
137 // existing CDATA sections.
138 Transform.appendEscapingCDATA(buf, event.getMessage().getFormattedMessage());
139 buf.append("]]></log4j:message>\r\n");
140 }
141 }
142
143 if (event.getContextStack().getDepth() > 0) {
144 buf.append("<log4j:NDC><![CDATA[");
145 Transform.appendEscapingCDATA(buf, event.getContextStack().toString());
146 buf.append("]]></log4j:NDC>\r\n");
147 }
148
149 final Throwable throwable = event.getThrown();
150 if (throwable != null) {
151 final List<String> s = getThrowableString(throwable);
152 buf.append("<log4j:throwable><![CDATA[");
153 for (final String str : s) {
154 Transform.appendEscapingCDATA(buf, str);
155 buf.append("\r\n");
156 }
157 buf.append("]]></log4j:throwable>\r\n");
158 }
159
160 if (locationInfo) {
161 final StackTraceElement element = event.getSource();
162 buf.append("<log4j:locationInfo class=\"");
163 buf.append(Transform.escapeTags(element.getClassName()));
164 buf.append("\" method=\"");
165 buf.append(Transform.escapeTags(element.getMethodName()));
166 buf.append("\" file=\"");
167 buf.append(Transform.escapeTags(element.getFileName()));
168 buf.append("\" line=\"");
169 buf.append(element.getLineNumber());
170 buf.append("\"/>\r\n");
171 }
172
173 if (properties && event.getContextMap().size() > 0) {
174 buf.append("<log4j:properties>\r\n");
175 for (final Map.Entry<String, String> entry : event.getContextMap().entrySet()) {
176 buf.append("<log4j:data name=\"");
177 buf.append(Transform.escapeTags(entry.getKey()));
178 buf.append("\" value=\"");
179 buf.append(Transform.escapeTags(String.valueOf(entry.getValue())));
180 buf.append("\"/>\r\n");
181 }
182 buf.append("</log4j:properties>\r\n");
183 }
184
185 buf.append("</log4j:event>\r\n\r\n");
186
187 return buf.toString();
188 }
189
190 /**
191 * Returns appropriate XML headers.
192 * @return a byte array containing the header.
193 */
194 @Override
195 public byte[] getHeader() {
196 if (!complete) {
197 return null;
198 }
199 final StringBuilder sbuf = new StringBuilder();
200 sbuf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
201 sbuf.append("<log4j:eventSet xmlns:log4j=\"http://logging.apache.org/log4j/\">\r\n");
202 return sbuf.toString().getBytes(getCharset());
203 }
204
205
206 /**
207 * Returns appropriate XML headers.
208 * @return a byte array containing the footer.
209 */
210 @Override
211 public byte[] getFooter() {
212 if (!complete) {
213 return null;
214 }
215 final StringBuilder sbuf = new StringBuilder();
216 sbuf.append("</log4j:eventSet>\r\n");
217 return sbuf.toString().getBytes(getCharset());
218 }
219
220 /**
221 * XMLLayout's content format is specified by:<p/>
222 * Key: "dtd" Value: "log4j.dtd"<p/>
223 * Key: "version" Value: "1.2"
224 * @return Map of content format keys supporting XMLLayout
225 */
226 public Map<String, String> getContentFormat() {
227 Map<String, String> result = new HashMap<String, String>();
228 result.put("dtd", "log4j.dtd");
229 result.put("version", "1.2");
230 return result;
231 }
232
233 @Override
234 /**
235 * @return The content type.
236 */
237 public String getContentType() {
238 return "text/xml";
239 }
240
241 List<String> getThrowableString(final Throwable throwable) {
242 final StringWriter sw = new StringWriter();
243 final PrintWriter pw = new PrintWriter(sw);
244 try {
245 throwable.printStackTrace(pw);
246 } catch (final RuntimeException ex) {
247 // Ignore any exceptions.
248 }
249 pw.flush();
250 final LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
251 final ArrayList<String> lines = new ArrayList<String>();
252 try {
253 String line = reader.readLine();
254 while (line != null) {
255 lines.add(line);
256 line = reader.readLine();
257 }
258 } catch (final IOException ex) {
259 if (ex instanceof InterruptedIOException) {
260 Thread.currentThread().interrupt();
261 }
262 lines.add(ex.toString());
263 }
264 return lines;
265 }
266
267 /**
268 * Create an XML Layout.
269 * @param locationInfo If "true" include the location information in the generated XML.
270 * @param properties If "true" include the thread context in the generated XML.
271 * @param complete If "true" include the XML header.
272 * @param charsetName The character set to use.
273 * @return An XML Layout.
274 */
275 @PluginFactory
276 public static XMLLayout createLayout(@PluginAttr("locationInfo") final String locationInfo,
277 @PluginAttr("properties") final String properties,
278 @PluginAttr("complete") final String complete,
279 @PluginAttr("charset") final String charsetName) {
280 final Charset charset = Charsets.getSupportedCharset(charsetName);
281 final boolean info = locationInfo == null ? false : Boolean.valueOf(locationInfo);
282 final boolean props = properties == null ? false : Boolean.valueOf(properties);
283 final boolean comp = complete == null ? false : Boolean.valueOf(complete);
284 return new XMLLayout(info, props, comp, charset);
285 }
286 }