1、maven配置:java
在porm.xml中加入:apache
<dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>3.3.2</version> </dependency>
若是不使用異步寫入日誌,第三個依賴能夠不加入。api
2、log4j 2.0的配置文件再也不支持properties文件,改用xml。具體以下:app
<?xml version="1.0" encoding="UTF-8"?> <!-- 修改status的值爲debug,能夠查看log4j的裝配過程;monitorInterval參數是多長時間重 新加載一遍該配置文件,這樣能夠在生產環境遭遇bug的時候,進行日誌級別調整 --> <configuration status="off" monitorInterval="60"> <properties> <!--日誌存儲目錄--> <property name="LOG_HOME">logs</property> <!-- 日誌備份目錄 --> <property name="BACKUP_HOME">logs/backup</property> </properties> <appenders> <!-- 定義控制檯輸出 --> <Console name="console" target="SYSTEM_OUT" follow="true"> <PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss.SSS z} %-5level %class{36} %L %M - %msg%xEx%n"/> </Console> <!-- 定義文件輸出 --> <RollingFile name="file" fileName="${LOG_HOME}/gvserver.log" filePattern="${BACKUP_HOME}/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz"> <PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss.SSS z} - %msg%xEx%n"/> <SizeBasedTriggeringPolicy size="5KB"/> </RollingFile> <!--異步寫入文件--> <Async name="async"> <AppenderRef ref="file"/> </Async> </appenders> <loggers> <!-- <asyncRoot level="DEBUG"> <appender-ref ref="file"/> <appender-ref ref="console"/> </asyncRoot>--> <root level="DEBUG"> <appender-ref ref="async"/> <appender-ref ref="console"/> </root> </loggers> </configuration>
3、示例程序:異步
package com.gvsoft.log; /** * Created with IntelliJ IDEA. * ProjectName:gvMsgRouting * Date: 15/8/14 * Time: 下午6:03 * Desc: */ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class TestLog { static Logger logger = LogManager.getLogger(TestLog.class.getName()); public void test() { logger.error("this is error log!"); logger.info("this is info log!"); logger.debug("this is debuf log!"); logger.warn("this is warn log!"); logger.fatal("this is fatal log!"); } public static void main(String arg[]){ TestLog testLog = new TestLog(); testLog.test(); } }