public
Last active

Fix html-not-escaped bug with logback's HTMLLayout

  • Download Gist
HTMLLayout.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
import static ch.qos.logback.core.CoreConstants.LINE_SEPARATOR;
 
import org.apache.commons.lang.StringEscapeUtils;
 
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.Converter;
 
/**
* Extend the {@link ch.qos.logback.classic.html.HTMLLayout} to escape HTML content.<br/>
* TODO remove when the bug if fixed by logback. See http://jira.qos.ch/browse/LBCLASSIC-180
* or http://stackoverflow.com/questions/2069135/how-to-make-xml-get-escaped-in-htmllayout-of-logback
* @author xhh
*/
public class HTMLLayout extends ch.qos.logback.classic.html.HTMLLayout {
 
@SuppressWarnings("unchecked")
public String doLayout(ILoggingEvent event) {
StringBuilder buf = new StringBuilder();
startNewTableIfLimitReached(buf);
 
boolean odd = true;
if (((counter++) & 1) == 0) {
odd = false;
}
 
String level = event.getLevel().toString().toLowerCase();
 
buf.append(LINE_SEPARATOR);
buf.append("<tr class=\"");
buf.append(level);
if (odd) {
buf.append(" odd\">");
} else {
buf.append(" even\">");
}
buf.append(LINE_SEPARATOR);
 
Converter<ILoggingEvent> c = head;
while (c != null) {
appendEventToBuffer(buf, c, event);
c = c.getNext();
}
buf.append("</tr>");
buf.append(LINE_SEPARATOR);
 
if (event.getThrowableProxy() != null) {
getThrowableRenderer().render(buf, event);
}
return buf.toString();
}
 
private void appendEventToBuffer(StringBuilder buf,
Converter<ILoggingEvent> c, ILoggingEvent event) {
buf.append("<td class=\"");
buf.append(computeConverterName(c));
buf.append("\">");
/*
* the following line is added by xhh to replace the original "buf.append(c.convert(event));"
* to escape HTML content
*/
buf.append("<pre>").append(StringEscapeUtils.escapeHtml(c.convert(event))).append("</pre>");
buf.append("</td>");
buf.append(LINE_SEPARATOR);
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.