Logger, Appenders and Layouts
Logback构建在三个主要的类上面:
Logger, Appender and Layouts
三个组件决定了日志的类型,格式,以及输出目的地
Logger类定义在loback-classic模块中, Appender 跟 Layout接口则定义在logback-core中,作为一个通用的模块,loback-core中没有Logger的概念。
日志等级Level的传递性
如果日志没有赋予level,则该Logger会从父Logger继承日志等级,父子关系如同java的包名:x.y作为x的子logger
如下
Logger name | Assigned level | Effective level |
---|---|---|
root | DEBUG | DEBUG |
X | INFO | INFO |
X.Y | none | INFO |
X.Y.Z | ERROR | ERROR |
日志输出的等级规定:
日志能输出的等级 | Logger有效等级 | |||||
TRACE | DEBUG | INFO | WARN | ERROR | OFF | |
---|---|---|---|---|---|---|
TRACE | YES | NO | NO | NO | NO | NO |
DEBUG | YES | YES | NO | NO | NO | NO |
INFO | YES | YES | YES | NO | NO | NO |
WARN | YES | YES | YES | YES | NO | NO |
ERROR | YES | YES | YES | YES | YES | NO |
ch.qos.logback.classic.Logger logger =
(ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.foo");
//日志等级被设置成了INFO
logger.setLevel(Level. INFO);
//该日志请求被允许,因为WARN的级别大于INFO
logger.warn("Low fuel level.");
// 该日志请求被拒绝,因为DEBUF小于INFO
logger.debug("Starting search for nearest gas station.");
Appender的叠加性
一个Appender就相当于一个日志输出目的地。一个Logger中被允许的日志请求,将会被转发到所有Appender上,包括该Logger的父Logger的Appender上,换句话说,Appender具有叠加性,如果Additivity Flag未被设置成false,日志将会向上输出。而Additivity Flag默认为True。
说明表如下
Logger Name | Attached Appenders | Additivity Flag | Output Targets | Comment |
---|---|---|---|---|
root | A1 | not applicable | A1 | Since the root logger stands at the top of the logger hierarchy, the additivity flag does not apply to it. |
x | A-x1, A-x2 | true | A1, A-x1, A-x2 | Appenders of "x" and of root. |
x.y | none | true | A1, A-x1, A-x2 | Appenders of "x" and of root. |
x.y.z | A-xyz1 | true | A1, A-x1, A-x2, A-xyz1 | Appenders of "x.y.z", "x" and of root. |
security | A-sec | false | A-sec | No appender accumulation since the additivity flag is set to false . Only appender A-sec will be used. |
security.access | none | true | A-sec | Only appenders of "security" because the additivity flag in "security" is set to false . |
采用何种日志输出编码
第一种(效率低):先对参数进行处理 。如果logger的日志级别不允许debug日志请求时,就做了无用功
logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
第二种(麻烦):先判断,在处理
if(logger.isDebugEnabled()) {
logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
}
第三种(推荐):内置先判断,再处理
logger.debug("The new entry is {}. It replaces {}.", entry, oldEntry);
//N多个参数,也可以使用数据对象
Object[] paramArray = {newVal, below, above};
logger.debug("Value {} was inserted between {} and {}.", paramArray);
Logger是如何运行的