1. 程式人生 > 實用技巧 >傻瓜式log4j配置日誌

傻瓜式log4j配置日誌

log4j配置日誌

maven 配置

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

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

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.2</version>
</dependency>

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%m%n" />
</Console>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>

log4j.properties

#所有日誌
log4j.rootLogger = DEBUG,stdout,file

log4j.logger.org.apache.ibatis=warn
log4j.logger.java.sql=warn
log4j.logger.org.springframework=warn

# Druid
log4j.logger.druid.sql=DEBUG
log4j.logger.druid.sql.DataSource=warn
log4j.logger.druid.sql.Connection=warn
log4j.logger.druid.sql.Statement=DEBUG
log4j.logger.druid.sql.ResultSet=warn
#設定包名的輸出級別
log4j.logger.cn.wdq=DEBUG,wdq

#控制檯輸出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.Threshold=DEBUG
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss}[ %p ]%m%n

#所有檔案輸出
log4j.appender.file = org.apache.log4j.FileAppender
#log4j.appender.file.File = ${webApp.root}/logs/allDEBUG.log
log4j.appender.file.File = src/main/java/logs/allDEBUG.log // 注意這裡是日誌的檔案目錄,對應的需要修改
log4j.appender.file.Encoding=UTF-8
log4j.appender.file.name = fileLogDemo
log4j.appender.file.Threshold=INFO
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss}[ %p ] %m%n
log4j.appender.file.append = true

#wdq下所有包的檔案輸出
log4j.appender.wdq = org.apache.log4j.FileAppender
#log4j.appender.wdq.File = ${webApp.root}/logs/package_wdq.log
log4j.appender.wdq.File = src/main/java/logs/package_wdq.log // 注意這裡是日誌的檔案目錄,對應的需要修改
log4j.appender.wdq.Encoding=UTF-8
log4j.appender.wdq.name = fileLogDemo
log4j.appender.wdq.Threshold=INFO
log4j.appender.wdq.layout=org.apache.log4j.PatternLayout
log4j.appender.wdq.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss}[ %p ]%m%n
log4j.appender.wdq.append = true

測試程式碼

package logTest;

import org.apache.log4j.Logger;
import org.junit.Test;


public class LoggerTest {
Logger logger= Logger.getLogger(LoggerTest.class);
@Test
public void printLogger(){
logger.error("直接輸出吧");
logger.info("hello world ");
try {

} catch (Exception e) {
e.printStackTrace();
}
}
}