示例1:
想要自定义layout,可以通过继承LayoutBase类,并重写doLayout方法,代码如下:
packagechapters.layouts;importch.qos.logback.classic.spi.ILoggingEvent;importch.qos.logback.core.CoreConstants;importch.qos.logback.core.LayoutBase;public class MySampleLayout extends LayoutBase{publicString doLayout(ILoggingEvent event) {
StringBuffer sbuf= new StringBuffer(128);
sbuf.append(event.getTimeStamp()-event.getLoggerContextVO().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_SEPARATOR);returnsbuf.toString();
}
}
编写完代码之后,需要在xml文件中配置自定义的layout,配置如下:
由于在自定义类MySampleLayout中已经实现了继承的doLayout()方法,因此,在标签中通过子标签指定已经实现转换功能的类MySampleLayout,该类MySampleLayout负责将ILoggingEvent类型事件转换为String类型。
4.为自定义的Layout添加参数
如何为 layout 增加选项?为 layout 或任何 logback 的其他组件添加属性非常简单:声明一个属性及 setter 方法接即可。MySampleLayout2 类包含两个属性。第一个是为输出添加的前缀。第二个是用于选择是否显示记录请求的线程名。
示例1:
代码如下:
packagechapters.layouts;importch.qos.logback.classic.spi.ILoggingEvent;importch.qos.logback.core.CoreConstants;importch.qos.logback.core.LayoutBase;public class MySampleLayout2 extends LayoutBase{
String prefix= null;boolean printThreadName = true;public voidsetPrefix(String prefix) {this.prefix =prefix;
}public void setPrintThreadName(booleanprintThreadName) {this.printThreadName =printThreadName;
}publicString 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(CoreConstants.LINE_SEPARATOR);returnsbuf.toString();
}
}
在配置里启用属性只需要有对应的 setter 方法即可。下面是 MySampleLayout2 所用的配置文件。
MyPrefix
false