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.lang.management.ManagementFactory;
026    import java.nio.charset.Charset;
027    import java.util.ArrayList;
028    import org.apache.logging.log4j.Level;
029    import org.apache.logging.log4j.core.Layout;
030    import org.apache.logging.log4j.core.LogEvent;
031    import org.apache.logging.log4j.core.config.Node;
032    import org.apache.logging.log4j.core.config.plugins.Plugin;
033    import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
034    import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute;
035    import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
036    import org.apache.logging.log4j.core.config.plugins.PluginFactory;
037    import org.apache.logging.log4j.core.util.Charsets;
038    import org.apache.logging.log4j.core.util.Constants;
039    import org.apache.logging.log4j.core.util.Transform;
040    
041    /**
042     * Outputs events as rows in an HTML table on an HTML page.
043     * <p>
044     * Appenders using this layout should have their encoding set to UTF-8 or UTF-16, otherwise events containing non ASCII
045     * characters could result in corrupted log files.
046     * </p>
047     */
048    @Plugin(name = "HtmlLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
049    public final class HtmlLayout extends AbstractStringLayout {
050    
051        private static final long serialVersionUID = 1L;
052    
053        private static final int BUF_SIZE = 256;
054    
055        private static final String TRACE_PREFIX = "<br />&nbsp;&nbsp;&nbsp;&nbsp;";
056    
057        private static final String REGEXP = Constants.LINE_SEPARATOR.equals("\n") ? "\n" : Constants.LINE_SEPARATOR + "|\n";
058    
059        private static final String DEFAULT_TITLE = "Log4j Log Messages";
060    
061        private static final String DEFAULT_CONTENT_TYPE = "text/html";
062    
063        public static final String DEFAULT_FONT_FAMILY = "arial,sans-serif";
064    
065        private final long jvmStartTime = ManagementFactory.getRuntimeMXBean().getStartTime();
066    
067        // Print no location info by default
068        private final boolean locationInfo;
069    
070        private final String title;
071    
072        private final String contentType;
073    
074        /**Possible font sizes */
075        public static enum FontSize {
076            SMALLER("smaller"), XXSMALL("xx-small"), XSMALL("x-small"), SMALL("small"), MEDIUM("medium"), LARGE("large"),
077            XLARGE("x-large"), XXLARGE("xx-large"),  LARGER("larger");
078    
079            private final String size;
080    
081            private FontSize(final String size) {
082                this.size = size;
083            }
084    
085            public String getFontSize() {
086                return size;
087            }
088    
089            public static FontSize getFontSize(final String size) {
090                for (final FontSize fontSize : values()) {
091                    if (fontSize.size.equals(size)) {
092                        return fontSize;
093                    }
094                }
095                return SMALL;
096            }
097    
098            public FontSize larger() {
099                return this.ordinal() < XXLARGE.ordinal() ? FontSize.values()[this.ordinal() + 1] : this;
100            }
101        }
102    
103        private final String font;
104        private final String fontSize;
105        private final String headerSize;
106    
107        private HtmlLayout(final boolean locationInfo, final String title, final String contentType, final Charset charset,
108                final String font, final String fontSize, final String headerSize) {
109            super(charset);
110            this.locationInfo = locationInfo;
111            this.title = title;
112            this.contentType = addCharsetToContentType(contentType);
113            this.font = font;
114            this.fontSize = fontSize;
115            this.headerSize = headerSize;
116        }
117    
118        private String addCharsetToContentType(final String contentType) {
119            if (contentType == null) {
120                return DEFAULT_CONTENT_TYPE + "; charset=" + getCharset();
121            }
122            return contentType.contains("charset") ? contentType : contentType + "; charset=" + getCharset();
123        }
124    
125        /**
126         * Format as a String.
127         *
128         * @param event The Logging Event.
129         * @return A String containing the LogEvent as HTML.
130         */
131        @Override
132        public String toSerializable(final LogEvent event) {
133            final StringBuilder sbuf = new StringBuilder(BUF_SIZE);
134    
135            sbuf.append(Constants.LINE_SEPARATOR).append("<tr>").append(Constants.LINE_SEPARATOR);
136    
137            sbuf.append("<td>");
138            sbuf.append(event.getTimeMillis() - jvmStartTime);
139            sbuf.append("</td>").append(Constants.LINE_SEPARATOR);
140    
141            final String escapedThread = Transform.escapeHtmlTags(event.getThreadName());
142            sbuf.append("<td title=\"").append(escapedThread).append(" thread\">");
143            sbuf.append(escapedThread);
144            sbuf.append("</td>").append(Constants.LINE_SEPARATOR);
145    
146            sbuf.append("<td title=\"Level\">");
147            if (event.getLevel().equals(Level.DEBUG)) {
148                sbuf.append("<font color=\"#339933\">");
149                sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
150                sbuf.append("</font>");
151            } else if (event.getLevel().isMoreSpecificThan(Level.WARN)) {
152                sbuf.append("<font color=\"#993300\"><strong>");
153                sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
154                sbuf.append("</strong></font>");
155            } else {
156                sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
157            }
158            sbuf.append("</td>").append(Constants.LINE_SEPARATOR);
159    
160            String escapedLogger = Transform.escapeHtmlTags(event.getLoggerName());
161            if (escapedLogger.isEmpty()) {
162                escapedLogger = "root";
163            }
164            sbuf.append("<td title=\"").append(escapedLogger).append(" logger\">");
165            sbuf.append(escapedLogger);
166            sbuf.append("</td>").append(Constants.LINE_SEPARATOR);
167    
168            if (locationInfo) {
169                final StackTraceElement element = event.getSource();
170                sbuf.append("<td>");
171                sbuf.append(Transform.escapeHtmlTags(element.getFileName()));
172                sbuf.append(':');
173                sbuf.append(element.getLineNumber());
174                sbuf.append("</td>").append(Constants.LINE_SEPARATOR);
175            }
176    
177            sbuf.append("<td title=\"Message\">");
178            sbuf.append(Transform.escapeHtmlTags(event.getMessage().getFormattedMessage()).replaceAll(REGEXP, "<br />"));
179            sbuf.append("</td>").append(Constants.LINE_SEPARATOR);
180            sbuf.append("</tr>").append(Constants.LINE_SEPARATOR);
181    
182            if (event.getContextStack() != null && !event.getContextStack().isEmpty()) {
183                sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : ").append(fontSize);
184                sbuf.append(";\" colspan=\"6\" ");
185                sbuf.append("title=\"Nested Diagnostic Context\">");
186                sbuf.append("NDC: ").append(Transform.escapeHtmlTags(event.getContextStack().toString()));
187                sbuf.append("</td></tr>").append(Constants.LINE_SEPARATOR);
188            }
189    
190            if (event.getContextMap() != null && !event.getContextMap().isEmpty()) {
191                sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : ").append(fontSize);
192                sbuf.append(";\" colspan=\"6\" ");
193                sbuf.append("title=\"Mapped Diagnostic Context\">");
194                sbuf.append("MDC: ").append(Transform.escapeHtmlTags(event.getContextMap().toString()));
195                sbuf.append("</td></tr>").append(Constants.LINE_SEPARATOR);
196            }
197    
198            final Throwable throwable = event.getThrown();
199            if (throwable != null) {
200                sbuf.append("<tr><td bgcolor=\"#993300\" style=\"color:White; font-size : ").append(fontSize);
201                sbuf.append(";\" colspan=\"6\">");
202                appendThrowableAsHtml(throwable, sbuf);
203                sbuf.append("</td></tr>").append(Constants.LINE_SEPARATOR);
204            }
205    
206            return sbuf.toString();
207        }
208    
209        @Override
210        /**
211         * @return The content type.
212         */
213        public String getContentType() {
214            return contentType;
215        }
216    
217        private void appendThrowableAsHtml(final Throwable throwable, final StringBuilder sbuf) {
218            final StringWriter sw = new StringWriter();
219            final PrintWriter pw = new PrintWriter(sw);
220            try {
221                throwable.printStackTrace(pw);
222            } catch (final RuntimeException ex) {
223                // Ignore the exception.
224            }
225            pw.flush();
226            final LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
227            final 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 (final IOException ex) {
235                if (ex instanceof InterruptedIOException) {
236                    Thread.currentThread().interrupt();
237                }
238                lines.add(ex.toString());
239            }
240            boolean first = true;
241            for (final String line : lines) {
242                if (!first) {
243                    sbuf.append(TRACE_PREFIX);
244                } else {
245                    first = false;
246                }
247                sbuf.append(Transform.escapeHtmlTags(line));
248                sbuf.append(Constants.LINE_SEPARATOR);
249            }
250        }
251    
252        /**
253         * Returns appropriate HTML headers.
254         * @return The header as a byte array.
255         */
256        @Override
257        public byte[] getHeader() {
258            final StringBuilder sbuf = new StringBuilder();
259            sbuf.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" ");
260            sbuf.append("\"http://www.w3.org/TR/html4/loose.dtd\">");
261            sbuf.append(Constants.LINE_SEPARATOR);
262            sbuf.append("<html>").append(Constants.LINE_SEPARATOR);
263            sbuf.append("<head>").append(Constants.LINE_SEPARATOR);
264            sbuf.append("<meta charset=\"").append(getCharset()).append("\"/>").append(Constants.LINE_SEPARATOR);
265            sbuf.append("<title>").append(title).append("</title>").append(Constants.LINE_SEPARATOR);
266            sbuf.append("<style type=\"text/css\">").append(Constants.LINE_SEPARATOR);
267            sbuf.append("<!--").append(Constants.LINE_SEPARATOR);
268            sbuf.append("body, table {font-family:").append(font).append("; font-size: ");
269            sbuf.append(headerSize).append(";}").append(Constants.LINE_SEPARATOR);
270            sbuf.append("th {background: #336699; color: #FFFFFF; text-align: left;}").append(Constants.LINE_SEPARATOR);
271            sbuf.append("-->").append(Constants.LINE_SEPARATOR);
272            sbuf.append("</style>").append(Constants.LINE_SEPARATOR);
273            sbuf.append("</head>").append(Constants.LINE_SEPARATOR);
274            sbuf.append("<body bgcolor=\"#FFFFFF\" topmargin=\"6\" leftmargin=\"6\">").append(Constants.LINE_SEPARATOR);
275            sbuf.append("<hr size=\"1\" noshade>").append(Constants.LINE_SEPARATOR);
276            sbuf.append("Log session start time " + new java.util.Date() + "<br>").append(Constants.LINE_SEPARATOR);
277            sbuf.append("<br>").append(Constants.LINE_SEPARATOR);
278            sbuf.append(
279                "<table cellspacing=\"0\" cellpadding=\"4\" border=\"1\" bordercolor=\"#224466\" width=\"100%\">");
280            sbuf.append(Constants.LINE_SEPARATOR);
281            sbuf.append("<tr>").append(Constants.LINE_SEPARATOR);
282            sbuf.append("<th>Time</th>").append(Constants.LINE_SEPARATOR);
283            sbuf.append("<th>Thread</th>").append(Constants.LINE_SEPARATOR);
284            sbuf.append("<th>Level</th>").append(Constants.LINE_SEPARATOR);
285            sbuf.append("<th>Logger</th>").append(Constants.LINE_SEPARATOR);
286            if (locationInfo) {
287                sbuf.append("<th>File:Line</th>").append(Constants.LINE_SEPARATOR);
288            }
289            sbuf.append("<th>Message</th>").append(Constants.LINE_SEPARATOR);
290            sbuf.append("</tr>").append(Constants.LINE_SEPARATOR);
291            return sbuf.toString().getBytes(getCharset());
292        }
293    
294        /**
295         * Returns the appropriate HTML footers.
296         * @return the footer as a byet array.
297         */
298        @Override
299        public byte[] getFooter() {
300            final StringBuilder sbuf = new StringBuilder();
301            sbuf.append("</table>").append(Constants.LINE_SEPARATOR);
302            sbuf.append("<br>").append(Constants.LINE_SEPARATOR);
303            sbuf.append("</body></html>");
304            return sbuf.toString().getBytes(getCharset());
305        }
306    
307        /**
308         * Create an HTML Layout.
309         * @param locationInfo If "true", location information will be included. The default is false.
310         * @param title The title to include in the file header. If none is specified the default title will be used.
311         * @param contentType The content type. Defaults to "text/html".
312         * @param charset The character set to use. If not specified, the default will be used.
313         * @param fontSize The font size of the text.
314         * @param font The font to use for the text.
315         * @return An HTML Layout.
316         */
317        @PluginFactory
318        public static HtmlLayout createLayout(
319                @PluginAttribute(value = "locationInfo", defaultBoolean = false) final boolean locationInfo,
320                @PluginAttribute(value = "title", defaultString = DEFAULT_TITLE) final String title,
321                @PluginAttribute("contentType") String contentType,
322                @PluginAttribute(value = "charset", defaultString = "UTF-8") final Charset charset,
323                @PluginAttribute("fontSize") String fontSize,
324                @PluginAttribute(value = "fontName", defaultString = DEFAULT_FONT_FAMILY) final String font) {
325            final FontSize fs = FontSize.getFontSize(fontSize);
326            fontSize = fs.getFontSize();
327            final String headerSize = fs.larger().getFontSize();
328            if (contentType == null) {
329                contentType = DEFAULT_CONTENT_TYPE + "; charset=" + charset;
330            }
331            return new HtmlLayout(locationInfo, title, contentType, charset, font, fontSize, headerSize);
332        }
333    
334        /**
335         * Creates an HTML Layout using the default settings.
336         *
337         * @return an HTML Layout.
338         */
339        public static HtmlLayout createDefaultLayout() {
340            return newBuilder().build();
341        }
342    
343        @PluginBuilderFactory
344        public static Builder newBuilder() {
345            return new Builder();
346        }
347    
348        public static class Builder implements org.apache.logging.log4j.core.util.Builder<HtmlLayout> {
349    
350            @PluginBuilderAttribute
351            private boolean locationInfo = false;
352    
353            @PluginBuilderAttribute
354            private String title = DEFAULT_TITLE;
355    
356            @PluginBuilderAttribute
357            private String contentType = null; // defer default value in order to use specified charset
358    
359            @PluginBuilderAttribute
360            private Charset charset = Charsets.UTF_8;
361    
362            @PluginBuilderAttribute
363            private FontSize fontSize = FontSize.SMALL;
364    
365            @PluginBuilderAttribute
366            private String fontName = DEFAULT_FONT_FAMILY;
367    
368            private Builder() {
369            }
370    
371            public Builder withLocationInfo(final boolean locationInfo) {
372                this.locationInfo = locationInfo;
373                return this;
374            }
375    
376            public Builder withTitle(final String title) {
377                this.title = title;
378                return this;
379            }
380    
381            public Builder withContentType(final String contentType) {
382                this.contentType = contentType;
383                return this;
384            }
385    
386            public Builder withCharset(final Charset charset) {
387                this.charset = charset;
388                return this;
389            }
390    
391            public Builder withFontSize(final FontSize fontSize) {
392                this.fontSize = fontSize;
393                return this;
394            }
395    
396            public Builder withFontName(final String fontName) {
397                this.fontName = fontName;
398                return this;
399            }
400    
401            @Override
402            public HtmlLayout build() {
403                // TODO: extract charset from content-type
404                if (contentType == null) {
405                    contentType = DEFAULT_CONTENT_TYPE + "; charset=" + charset;
406                }
407                return new HtmlLayout(locationInfo, title, contentType, charset, fontName, fontSize.getFontSize(),
408                    fontSize.larger().getFontSize());
409            }
410        }
411    }