首先,認識一下三胞胎
- log4j是apache實現的一個開源日誌組件
- logback同樣是由log4j的作者設計完成的,擁有更好的特性,用來取代log4j的一個日誌框架,是slf4j的原生實現
- Log4j2是log4j 1.x和logback的改進版,據說採用了一些新技術(無鎖異步、等等),使得日誌的吞吐量、性能比log4j 1.x提高10倍,並解決了一些死鎖的bug,而且配置更加簡單靈活
使用slf4j+log4j和直接用log4j的區別
slf4j是對所有日誌框架制定的一種規範、標準、接口,並不是一個框架的具體的實現,因爲接口並不能獨立使用,需要和具體的日誌框架實現配合使用(如log4j、logback),使用接口的好處是當項目需要更換日誌框架的時候,只需要更換jar和配置,不需要更改相關java代碼
log4j、logback、log4j2都是一種日誌具體實現框架,所以既可以單獨使用也可以結合slf4j一起搭配使用
一、導入需要使用的jar包(slf4j+log4j2)
springboot項目中需導入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
繞坑:如項目中有導入spring-boot-starter-web依賴包記得去掉spring自帶的日誌依賴spring-boot-starter-logging,如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
二、開始配置
springboot方式:
application.properties中添加配置 logging.config=classpath:log4j2_dev.xml, log4j2_dev.xml是你創建的log4j2的配置文件名,放在resources下,如放在其他路徑則對應修改
配置文件的格式:log2j配置文件可以是xml格式的,也可以是json格式的,
配置文件的位置:log4j2默認會在classpath目錄下尋找log4j2.xml、log4j.json、log4j.jsn等名稱的文件,如果都沒有找到,則會按默認配置輸出,也就是輸出到控制檯,也可以對配置文件自定義位置(需要在web.xml中配置),一般放置在src/main/resources根目錄下即可
貼上log4j2_dev.xml的配置再來講解
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<properties>
<property name="LOG_HOME">D:/logs</property>
<property name="FILE_NAME">mylog</property>
<property name="log.sql.level">info</property>
</properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %l - %msg%n" />
</Console>
<RollingRandomAccessFile name="RollingRandomAccessFile" fileName="${LOG_HOME}/${FILE_NAME}.log" filePattern="${LOG_HOME}/$${date:yyyy-MM}/${FILE_NAME}-%d{yyyy-MM-dd HH-mm}-%i.log">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %l - %msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10 MB"/>
</Policies>
<DefaultRolloverStrategy max="20"/>
</RollingRandomAccessFile>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console" />
<AppenderRef ref="RollingRandomAccessFile" />
</Root>
<Logger name="org.yxy.mapper" level="${log.sql.level}" additivity="false">
<AppenderRef ref="Console" />
</Logger>
</Loggers>
</Configuration>