`

log4j 入门实例 (一) HelloLog4j

阅读更多
首先要下载官网的jar包以及说明文档文件。
文件里包含了log4j.properties,该文件用于配置日志信息,级别操作。


http://archive.apache.org/dist/logging/log4j/1.2.16/


下面是log4j的helloworld实例。


1. 导入log4j.jar包。

2. 创建HelloLog4j.java

public class HelloLog4J
{	
	private static Logger logger=Logger.getLogger(HelloLog4J.class);
	
	public static void main(String[] args)
	{	
		System.out.println("hello log4j");
		logger.debug("In the main method");
		logger.info("This is info message");
		logger.error("This is error message");
	}
}


直接运行以上代码, 会有以下console信息:
hello log4j
log4j:WARN No appenders could be found for logger (com.lj.log4j.HelloLog4J).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.


这是因为我们没有导入所谓的'appender', 也就是log4j.properties文件。

因此我们需要在classpath路径下创建一个log4j.properties文件。

3. 创建log4j.properties:

#set log level to debug level.
log4j.rootLogger=debug,appender1

#set the log appender of the information. In this case, it is set as Console.
log4j.appender.appender1=org.apache.log4j.ConsoleAppender

#set the layout of the log informaton
log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout


再次运行HelloLog4j,我们就会看到不同的Console信息:

hello log4j
[main] DEBUG com.lj.log4j.HelloLog4J - In the main method
[main] INFO com.lj.log4j.HelloLog4J - This is info message
[main] ERROR com.lj.log4j.HelloLog4J - This is error message

这里就输出了我们所期待的信息。
[main]表示我们是在main函数当中运行的这个代码.
DEBUG, INFO, ERROR表示不同的log级别。
com.lj.log4j.HelloLog4J是包+类名信息。
最后输出log信息。

4. 设置log级别
在上面的例子中,我们所设置的log输出级别是debug->log4j.rootLogger=debug,appender1
这里我们可以修改log级别,例如设置为info,可以看到以下的输出内容:
hello log4j
[main] INFO com.lj.log4j.HelloLog4J - This is info message
[main] ERROR com.lj.log4j.HelloLog4J - This is error message


也就是说,debug信息就没了。
原因是log4j的信息输出是要根据级别的, debug和info的级别是debug<info.
只有高于所设定的级别的信息才会被输出
因此这里的debug就会被屏蔽掉了。

假如我们将输出级别设置为error, 那么这次就只有error信息会被输出了
[main] ERROR com.lj.log4j.HelloLog4J - This is error message
原因是info的级别要小于我们设定的error级别。

总体来说log4j的级别顺序如下:
DEBUG < INFO < WARN < ERROR < FATAL
简而言之, 当设定为debug的时候,所有log4j的信息都会被输出。
而设定为fatal时, 就只有logger.fatal里面的信息会被输出。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics