阅读Logback文档笔记--LogBack架构

来源:互联网 发布:家具拆单下料软件 编辑:程序博客网 时间:2024/05/18 00:56
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 nameAssigned levelEffective levelrootDEBUGDEBUGXINFOINFOX.YnoneINFOX.Y.ZERRORERROR

日志输出的等级规定:
日志能输出的等级Logger有效等级TRACEDEBUGINFOWARNERROROFFTRACEYESNONONONONODEBUGYESYESNONONONOINFOYESYESYESNONONOWARNYESYESYESYESNONOERRORYESYESYESYESYESNO

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 NameAttached AppendersAdditivity FlagOutput TargetsCommentrootA1not applicableA1Since the root logger stands at the top of the logger hierarchy, the additivity flag does not apply to it.xA-x1, A-x2trueA1, A-x1, A-x2Appenders of "x" and of root.x.ynonetrueA1, A-x1, A-x2Appenders of "x" and of root.x.y.zA-xyz1trueA1, A-x1, A-x2, A-xyz1Appenders of "x.y.z", "x" and of root.securityA-secfalseA-secNo appender accumulation since the additivity flag is set to false. Only appender A-sec will be used.security.accessnonetrueA-secOnly 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是如何运行的
0 0