概述
log4j是一款非常方便而且强大的开源日志项目,在经过简单的配置后,可以达到相当不错的效果。
头脑一热决定对log4j的源码进行一定的阅读,其初衷是希望通过源码的阅读,提高写代码的能力。
log4j其核心概念可分为:
logger 日志接收器,即程序员在自己的代码中使用如logger.error(...)的形式记录日志。
append 日志写出器,将logger接收到的日志信息写入到各种设备,如文件,控制台。
layout 日志格式化器,将输入的日志先进行格式化,再输出。
log4j将日志分为了几个级别,由低到高分别为:DEBUG < INFO < WARN < ERROR < FATAL。
若低级别的日志能输出,则比之级别高的日志也能输出。
UML
第一次画UML,多少有点紧张...
主要是希望通过UML图能够反映出logger的组织结构,及logger与其他组件的关系,因此很多因素被忽
略了。之后的说明都将对照着这个图来。
Logger
Logger继承自Category,而在Category有这样的说明
This class has been deprecated and replaced by the {@link Logger} <em>subclass</em></b></font>. It will be kept around to preserve backward compatibility until mid 2003.
name:作为自己的标识,在工厂方法中通过name来new出Logger实例。
level:每个Logger都有一个Level属性,在输出日志时,将通过方法getEffectiveLevel()获取到本身
有效的Level,以确定是否可以输出该条日志。稍后将详细说明级别判断流程。
parent:每个Logger都有个父结点,父子关系将在LoggerRepository中生成。正因为有了父子关系
所以在getEffectiveLevel方法中,实际上是向父结点方向遍历,找到第一个不为空的Level。也就是
说,若不明确指定当前结点的level,则使用父结点的level,在之后LoggerRepository的介绍时,会
知道,有一个公共的父结点RootLogger。
1 /** 2 Starting from this category, search the category hierarchy for a 3 non-null level and return it. Otherwise, return the level of the 4 root category. 5 6 <p>The Category class is designed so that this method executes as 7 quickly as possible. 8 */ 9 public 10 Level getEffectiveLevel() { 11 for(Category c = this; c != null; c=c.parent) { 12 if(c.level != null) { 13 return c.level; 14 } 15 } 16 return null; // If reached will cause an NullPointerException. 17 }