Log4j基础

   New  Java Project     demolog4j

   在 Build Path 添加 log4j 的类库

  

   1>新建类 Log4jTest

public class Log4jTest {

	public static void main(String[] args) {
		
		//生成Logger类型的对象
		//调用静态方法getLogger方法
		//传入当前类的名字
		Logger logger=Logger.getLogger(Log4jTest.class);
		
		//使用默认的配置
		BasicConfigurator.configure();
		//设置级别
		logger.setLevel(Level.INFO);
		
		logger.debug("This is debug message");
		logger.info("This is info message");
		logger.warn("This is warn message");
		logger.error("This is error message");
		logger.fatal("This is fatal message");
	
	}
}

 

   代码输出

0 [main] INFO Log4jTest  - This is info message
0 [main] WARN Log4jTest  - This is warn message
0 [main] ERROR Log4jTest  - This is error message
0 [main] FATAL Log4jTest  - This is fatal message

 

    2>新建类  HelloLog4j

public class HelloLog4j {
	
	//生成Logger类型的对象
	//调用静态方法getLogger方法
	//传入当前类的名字
	private static Logger logger=Logger.getLogger(HelloLog4j.class);
	
	public static void main(String args[]){
		System.out.println("This is println message");
		logger.debug("This is debug message");
		logger.info("This is info message");
		logger.error("This is error message");
	}
	
}

 

    在src目录下  New File  log4j.properties

log4j.rootLogger=debug,appender1                                  #设置log4j输出级别是debug
log4j.appender.appender1=org.apache.log4j.ConsoleAppender         #日志信息到终端进行输出
log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout       #输出的样式

 

    代码输出

This is println message
[main] DEBUG com.test.log4j.HelloLog4j - This is debug message
[main] INFO com.test.log4j.HelloLog4j - This is info message
[main] ERROR com.test.log4j.HelloLog4j - This is error message

   

你可能感兴趣的:(apache,log4j)