log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="300">
<properties>
<property name="INFO_HOME">logs/info</property>
<property name="ERROR_HOME">logs/error</property>
<property name="FILE_EOOR_NAME">eplan_error</property>
<property name="FILE_INFO_NAME">eplan_info</property>
</properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} -
%msg%n" />
</Console>
<RollingRandomAccessFile name="InfoFile"
fileName="${INFO_HOME}/${FILE_INFO_NAME}.log"
filePattern="${INFO_HOME}/$${date:yyyy-MM-dd}/info/${FILE_INFO_NAME}-%d{yyyy-MM-dd}-%i.log">
<Filters>
<ThresholdFilter level="warn" onMatch="DENY"
onMismatch="NEUTRAL" />
<ThresholdFilter level="info" onMatch="ACCEPT"
onMismatch="DENY" />
</Filters>
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss} %logger{36} -
%msg%n" />
<Policies>
<TimeBasedTriggeringPolicy interval="1" />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="3" />
</RollingRandomAccessFile>
<RollingRandomAccessFile name="ErrorFile"
fileName="${ERROR_HOME}/${FILE_EOOR_NAME}.log"
filePattern="${ERROR_HOME}/$${date:yyyy-MM-dd}/error/${FILE_EOOR_NAME}-%d{yyyy-MM-dd}-%i.log">
<Filters>
<ThresholdFilter level="fatal" onMatch="DENY"
onMismatch="NEUTRAL" />
<ThresholdFilter level="error" onMatch="ACCEPT"
onMismatch="DENY" />
</Filters>
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level
%logger{36} - %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy interval="1" />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingRandomAccessFile>
</Appenders>
<Loggers>
<Root level="trace">
<AppenderRef ref="Console" />
<AppenderRef ref="InfoFile" />
<AppenderRef ref="ErrorFile" />
</Root>
</Loggers>
</Configuration>
TestLog4j2.java
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @author ZL
* @date 2020年2月26日 上午10:32:58
* @Description
*/
public class TestLog4j2 {
private static final Logger logger = LogManager.getLogger(TestLog4j2.class);
public static void main(String[] args) {
try {
int i = 1/0;
} catch (Exception e) {
logger.error("使用 + 號連接直接輸出 e :"+e);
System.out.println("--------------------------------------------");
logger.error("使用 + 號連接直接輸出 e.toString() :"+e.toString());
System.out.println("--------------------------------------------");
logger.error("使用 + 號連接直接輸出 e.getMessage() :"+e.getMessage());
System.out.println("--------------------------------------------");
logger.error("使用 绩郎,號 且第二個(gè)參數(shù)為Throwable :",e);
System.out.println("--------------------------------------------");
logger.error("第二個(gè)參數(shù)為Throwable,使用分隔符{} :",e);
System.out.println("--------------------------------------------");
logger.error("第二個(gè)參數(shù)為Object,使用分隔符{} :","AAA");
System.out.println("--------------------------------------------");
}
}
}