一、什么是Layout?
Layout是logback中负责把日志事件转换成成字符串的组件,接口如下:
public interface Layout<E> extends ContextAware, LifeCycle { String doLayout(E event); String getFileHeader(); String getPresentationHeader(); String getFileFooter(); String getPresentationFooter(); String getContentType(); }
二、自定义Layout
1、继承自LayoutBase接口即可,如下:
package chapters.layouts; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.LayoutBase; public class MySampleLayout extends LayoutBase<ILoggingEvent> { public String doLayout(ILoggingEvent event) { StringBuffer sbuf = new StringBuffer(128); sbuf.append(event.getTimeStamp() - event.getLoggingContextVO.getBirthTime()); sbuf.append(" "); sbuf.append(event.getLevel()); sbuf.append(" ["); sbuf.append(event.getThreadName()); sbuf.append("] "); sbuf.append(event.getLoggerName(); sbuf.append(" - "); sbuf.append(event.getFormattedMessage()); sbuf.append(CoreConstants.LINE_SEP); return sbuf.toString(); } }
日志输出如下:
<configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder"> <layout class="chapters.layouts.MySampleLayout" /> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration>
2、包含自定义属性的layout,自定义实现如下:
package chapters.layouts; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.LayoutBase; public class MySampleLayout2 extends LayoutBase<ILoggingEvent> { String prefix = null; boolean printThreadName = true; public void setPrefix(String prefix) { this.prefix = prefix; } public void setPrintThreadName(boolean printThreadName) { this.printThreadName = printThreadName; } public String doLayout(ILoggingEvent event) { StringBuffer sbuf = new StringBuffer(128); if (prefix != null) { sbuf.append(prefix + ": "); } sbuf.append(event.getTimeStamp() - event.getLoggerContextVO().getBirthTime()); sbuf.append(" "); sbuf.append(event.getLevel()); if (printThreadName) { sbuf.append(" ["); sbuf.append(event.getThreadName()); sbuf.append("] "); } else { sbuf.append(" "); } sbuf.append(event.getLoggerName()); sbuf.append(" - "); sbuf.append(event.getFormattedMessage()); sbuf.append(LINE_SEP); return sbuf.toString(); } }
配置文件如下:
<configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder"> <layout class="chapters.layouts.MySampleLayout2"> <prefix>MyPrefix</prefix> <printThreadName>false</printThreadName> </layout> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration>
有效转换词以及相关选项如下表:四、格式修饰符
通过格式修饰符可以改变数据域最小和最大宽度,格式修饰符位于百分号和转换词之间,默认格式是右调整,左调整可以使用(-)减号,下面是一些示例:下面这张表是格式修饰符截取的例子,注意方括号不是日志输出的一部分,只用来分割日志输出的宽度。