在这里我们试着添加配置文件。
另外,我们需要注意的是2.0版本中的配置只能为Xml和Json。
测试代码为:
package com.foo; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Bar { static Logger logger = LogManager.getLogger(Bar.class.getName()); public boolean doIt() { logger.entry(); //Log entry to a method logger.error("Did it again!"); //Log a message object with the ERROR level logger.exit(); //Log exit from a method return false; } }
import com.foo.Bar; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class MyApp { // Define a static logger variable so that it references the // Logger instance named "MyApp". private static Logger logger = LogManager.getLogger(MyApp.class.getName()); public static void main(String[] args) { // Set up a simple configuration that logs on the console. logger.trace("Entering application."); //Log a message object with the TRACE level. Bar bar = new Bar(); if (!bar.doIt()) { logger.error("Didn't do it."); } logger.trace("Exiting application."); } }
没有配置文件情况下的输出为:
17:13:01.540 [main] ERROR com.foo.Bar - Did it again! 17:13:01.540 [main] ERROR MyApp - Didn't do it.由之前的例子我们不难知道,这是因为缺省配置文件的优先级默认为Error的缘故。
下面的配置文件在效果上等于缺省情况的下的配置文件:
<?xml version="1.0" encoding="UTF-8"?> <configuration status="OFF"> <appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </Console> </appenders> <loggers> <root level="error"> <appender-ref ref="Console"/> </root> </loggers> </configuration>
我们对上面的配置文件修改之后,再运行程序:
<?xml version="1.0" encoding="UTF-8"?> <configuration status="OFF"> <appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </Console> </appenders> <loggers> <root level="trace"> <appender-ref ref="Console"/> </root> </loggers> </configuration>
输出结果为:
11:43:57.703 [main] TRACE edu.hrbeu.tested.MyApp - Entering application. 11:43:57.718 [main] TRACE com.foo.Bar - entry 11:43:57.718 [main] ERROR com.foo.Bar - Did it again! 11:43:57.718 [main] TRACE com.foo.Bar - exit 11:43:57.718 [main] ERROR edu.hrbeu.tested.MyApp - Didn't do it. 11:43:57.718 [main] TRACE edu.hrbeu.tested.MyApp - Exiting application.将优先级设置为trace后就可以显式的跟踪程序的执行过程。
若是我们想去掉除com.foo.Bar以外所有的trace输出,我们可以增加一个新的注册事件,如下所示
<?xml version="1.0" encoding="UTF-8"?> <configuration status="OFF"> <appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </Console> </appenders> <loggers> <logger name="com.foo.Bar" level="trace" additivity="false"> <appender-ref ref="Console"/> </logger> <root level="error"> <appender-ref ref="Console"/> </root> </loggers> </configuration>
程序输出为:
11:53:31.796 [main] TRACE com.foo.Bar - entry 11:53:31.796 [main] ERROR com.foo.Bar - Did it again! 11:53:31.796 [main] TRACE com.foo.Bar - exit 11:53:31.796 [main] ERROR edu.hrbeu.tested.MyApp - Didn't do it.