1. 程式人生 > >Log4j2配置

Log4j2配置

log4j2

1.需要的jar包

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.8.2</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.8.2</version>
</dependency>

2.配置log4j2.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="logs_home">${sys:user.dir}/logs</Property>
        <Property name="logs_size">100MB</Property>
        <Property name="level">DEBUG</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
        <PatternLayout pattern="[%p][%d{yyyy-MM-dd HH:mm:ss}][%c][%t] : %m%n" />
    </Console>
    <File  name="allLog" fileName="${logs_home}/logs.log" >
        <PatternLayout pattern="[%p][%d{yyyy-MM-dd HH:mm:ss}][%c][%t] : %m%n"/>
    </File>
    </Appenders>
    <Loggers>
        <Logger name="com" level="${level}">
            <AppenderRef ref="console" />
        </Logger>
        <Root level="${level}">
            <AppenderRef ref="console" />
            <AppenderRef ref="allLog" />
        </Root>
    </Loggers>
</Configuration>

a.默認是放置在src的目錄下面,log4j2的jar包會默認加載這個位置的配置文件。

b.也可以自行配置加載路徑

String log4j=System.getProperty("user.dir") + "/config/log4j2.xml";//log4j2的地址
ConfigurationSource source = new ConfigurationSource(new FileInputStream(log4j));
Configurator.initialize(null,source);// 加載log4j2.xml配置文件

3.使用方式

public class String2ImageUtilTest {
	private static final Logger LOGGER = LogManager.getLogger(String2ImageUtilTest.class);
 	
	@Test
	public void transform() {
		String str ="Hello World! 你好,世界";
		LOGGER.info(str);
	}

}


Log4j2配置