log4j 2.x读取配置文件以及使用

时间:2022-10-24 21:53:44

                                          log4j 2.x读取配置文件以及使用

1.引用log4j jar包

    

                <dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jcl</artifactId>
<version>2.2</version>
</dependency>
2.log4j2.x的版本提供了ConfigurationSource和Configurator这两个类。可以使用它们进行手动的加载任意位置的配置文件信息。

  1)log4j.properties

     

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="myConsole" target="SYSTEM_OUT">
<PatternLayout pattern="[%d{MM-dd HH:mm:ss,SSS} %-5p] %c{2\} - %m%n%ex" />
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="myConsole" />
</Root>
</Loggers>
</Configuration>

log4j 2.x读取配置文件以及使用

   2)代码

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;

public class TestLog {

public static void main(String args[]){
try {
String config=System.getProperty("user.dir");//获取程序的当前路径
System.out.println("config="+config);
ConfigurationSource source = new ConfigurationSource(new FileInputStream(config+"\\src\\main\\java\\log4j.properties"));
Configurator.initialize(null, source);

Logger logger = LogManager.getLogger(TestLog.class);
logger.log(Level.INFO, "你好,北京");
logger.info("bejing welcome you");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}
运行结果:

    config=D:\Users\Administrator\workspace23\Test
    [11-23 10:40:22,523 INFO ]  ma\.ja\.TestLog - 你好,北京
    [11-23 10:40:22,524 INFO ]  ma\.ja\.TestLog - bejing welcome you