log4j-loggers
Log4j有三个主要组件,loggers, appenders and layouts. 三个类型的组件通过message type and level 相关协调可以让开发者记录log messages.
Logger层 对于logging api超越普通的System.out.println首先也就是最重要的好处他能够禁用某些日志语句,同时允许其他人可以正常print.这种能力假设为loggin space.也就说是所以可能的logging statement的space,是根据一些开发者选择的标准进行分类.这一观察使得我们选择类别作以包的中心开概念.然而,在log4j version1.2,Logger class取代了Category class.对于那些熟悉log4j早期版本,Logger类可以被视为仅仅是Category类的一个别名. Loggers被称为实体,Loggers名字区别大小写,他们遵循的是分层的命名规则 Nameing hierarchy 如果一个logger的名字由一个dot后代作为logger名称的前缀,那么会被认为是另一个logger的祖先,如果本身和后代logger之间没有始祖.如果本身和后代logger之间没有始祖.一个logger是另一个child logger的parent,
例如,"com.foo" logger是"com.foo.Bar"logger的parent,类似 "java"是"java.util"parent,是"java.util.Vector"的祖先. 这个命名方式为大多数开发者所熟悉. root logger位于logger hierarchy的最项层,以下两方面比较特殊. 1.一直存在. 2.不能通过名字检索. 调用logger.getRootLogger方法可以取得.所有其他的loggers通过Logger.getLogger方法进行实例化.方法需要一个logger名称作为参数.以下是Logger class 的一些基础方法.
package org.apache.log4j;
public class Logger {
// Creation & retrieval methods:
public static Logger getRootLogger();
public static Logger getLogger(String name);
// printing methods:
public void trace(Object message);
public void debug(Object message);
public void info(Object message);
public void warn(Object message);
public void error(Object message);
public void fatal(Object message);
// generic printing method:
public void log(Level l, Object message);
}
Loggers可以指定levels TRACE, DEBUG, INFO, WARN, ERROR and FATAL 这些定义在org.apache.log4j.Level class中.可以自定义 Level class的sub-classing. 如果一个logger没有指定level,更正式的说,他会从离他最近白ancestor继承 level. Level Inheritance 一个logger c的继承level等于logger hierarchy中第一个非null level,在C开始,并在hierarchy里向着root logger进行处理 确保所有loggers可以继承一个level,root总会指定一个level. Basic Selection Rule 如果p >= q.,那么是执行logger level q 中一个log请求level为p(指定或是继承,以适用者为准). 此规则是log4j的核心,假设level是有序的,对于标准level,DEBUG < INFO < WARN < ERROR < FATAL. 以下是这个规则的例子.
// get a logger instance named "com.foo"
Logger logger = Logger.getLogger("com.foo");
// Now set its level. Normally you do not need to set the
// level of a logger programmatically. This is usually done
// in configuration files.
logger.setLevel(Level.INFO);
Logger barlogger = Logger.getLogger("com.foo.Bar");
// This request is enabled, because WARN >= INFO.
logger.warn("Low fuel level.");
// This request is disabled, because DEBUG < INFO.
logger.debug("Starting search for nearest gas station.");
// The logger instance barlogger, named "com.foo.Bar",
// will inherit its level from the logger named
// "com.foo" Thus, the following request is enabled
// because INFO >= INFO.
barlogger.info("Located nearest gas station.");
// This request is disabled, because DEBUG < INFO.
barlogger.debug("Exiting gas station search");