本文主要研究一下logback的StatusListener
ch/qos/logback/core/status/StatusListener.java
/**
* A StatusListener registered with logback context's {@link StatusManager} will
* receive notification of every incoming {@link Status status} message.
*
* @author Ceki Gülcü
*/
public interface StatusListener {
void addStatusEvent(Status status);
}
StatusListener定义了addStatusEvent方法,注册到logback上下文的StatusManager的StatusListener将接收每个传入状态消息
ch/qos/logback/core/status/NopStatusListener.java
public class NopStatusListener implements StatusListener {
public void addStatusEvent(Status status) {
// nothing to do
}
}
NopStatusListener实现了StatusListener,它的addStatusEvent是空操作
abstract public class OnPrintStreamStatusListenerBase extends ContextAwareBase implements StatusListener, LifeCycle {
boolean isStarted = false;
static final long DEFAULT_RETROSPECTIVE = 300;
long retrospectiveThresold = DEFAULT_RETROSPECTIVE;
/**
* The prefix to place before each status message
* @since 1.1.10
*/
String prefix;
/**
* The PrintStream used by derived classes
* @return
*/
abstract protected PrintStream getPrintStream();
public void addStatusEvent(Status status) {
if (!isStarted)
return;
print(status);
}
private void print(Status status) {
StringBuilder sb = new StringBuilder();
if(prefix != null)
sb.append(prefix);
StatusPrinter.buildStr(sb, "", status);
getPrintStream().print(sb);
}
//......
}
OnPrintStreamStatusListenerBase声明实现了StatusListener接口,它是一个抽象类,其addStatusEvent方法执行print,而print则先添加prefix,再添加status,最后通过getPrintStream抽象方法获取PrintStream,然后进行print
ch/qos/logback/core/status/OnConsoleStatusListener.java
/**
* Print all new incoming status messages on the console (System.out).
*
* @author Ceki Gülcü
*/
public class OnConsoleStatusListener extends OnPrintStreamStatusListenerBase {
@Override
protected PrintStream getPrintStream() {
return System.out;
}
}
OnConsoleStatusListener继承了OnPrintStreamStatusListenerBase,其getPrintStream返回的是System.out
ch/qos/logback/core/status/OnErrorConsoleStatusListener.java
/**
* Print all new incoming status messages on the error console (System.err).
*
* @author Ceki Gülcü
* @since 1.0.8
*/
public class OnErrorConsoleStatusListener extends OnPrintStreamStatusListenerBase {
@Override
protected PrintStream getPrintStream() {
return System.err;
}
}
OnErrorConsoleStatusListener继承了OnPrintStreamStatusListenerBase,其getPrintStream返回的是System.err
ch/qos/logback/core/status/StatusListenerAsList.java
/**
* Collect all incoming events in a list.
*
* @author Ceki Gülcü
*
*/
public class StatusListenerAsList implements StatusListener {
List statusList = new ArrayList();
public void addStatusEvent(Status status) {
statusList.add(status);
}
public List getStatusList() {
return statusList;
}
}
StatusListenerAsList实现了StatusListener接口,其addStatusEvent将status添加到statusList
logback的StatusListener用于打印logback内部的status信息,它有NopStatusListener实现及OnPrintStreamStatusListenerBase的实现(OnConsoleStatusListener
及OnErrorConsoleStatusListener
),即往System.out或者err打印。