1. 程式人生 > 程式設計 >SpringBoot使用Log4j的知識點整理

SpringBoot使用Log4j的知識點整理

log4j、logback、Log4j2簡介

  • log4j是apache實現的一個開源日誌元件
  • logback同樣是由log4j的作者設計完成的,擁有更好的特性,用來取代log4j的一個日誌框架,是slf4j的原生實現
  • Log4j2是log4j 1.x和logback的改進版,採用了一些新技術(無鎖非同步、等等),使得日誌的吞吐量、效能比log4j 1.x提高10倍,並解決了一些死鎖的bug,而且配置更加簡單靈活

slf4j+log4j和直接用log4j的區別

slf4j是對所有日誌框架制定的一種規範、標準、介面,並不是一個框架的具體的實現,因為介面並不能獨立使用,需要和具體的日誌框架實現配合使用(如log4j、logback),使用介面的好處是當專案需要更換日誌框架的時候,只需要更換jar和配置,不需要更改相關java程式碼。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestSlf4j {
 //Logger和LoggerFactory匯入的是org.slf4j包
 private final static Logger logger = LoggerFactory.getLogger(TestSlf4j.class);
}

log4j、logback、log4j2都是一種日誌具體實現框架,所以既可以單獨使用也可以結合slf4j一起搭配使用

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
 
public class TestLog4j {
 // Logger和LogManager匯入的是org.apache.logging包
 private static final Logger LOG = LogManager.getLogger(TestLog4j.class); 
}

匯入需要使用的jar包(slf4j+log4j2)

log4j2

如專案中有匯入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專案中需匯入log4j2

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

log4j

如果要使用log4j,則把log4j2的座標替換為下面的這個,依然要排除原有的spring-boot-starter-logging。

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-log4j</artifactId>
 <version>1.3.8.RELEASE</version>
</dependency>

如果使用log4j,直接在resource下方新建log4j.properties即可。

https://www.jb51.net/article/143488.htm

配置XML位置Log4j2

Springboot方式

application.properties 中新增配置 logging.config=classpath:log4j2_dev.xml,log4j2_dev.xml是你建立的log4j2的配置檔名,放在resources下,如放在其他路徑則對應修改

Web工程方式

<context-param> 
 <param-name>log4jConfiguration</param-name> 
 <param-value>/WEB-INF/conf/log4j2.xml</param-value> 
</context-param> 
 
<listener> 
 <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class> 
</listener>

Java方式

public static void main(String[] args) throws IOException { 
 File file = new File("D:/log4j2.xml"); 
 BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); 
 final ConfigurationSource source = new ConfigurationSource(in); 
 Configurator.initialize(null,source); 
 
 Logger logger = LogManager.getLogger("myLogger"); 
}

配置檔案的格式:log2j配置檔案可以是xml格式的,也可以是json格式的

配置檔案的位置:log4j2預設會在classpath目錄下尋找log4j2.xml、log4j.json、log4j.jsn等名稱的檔案,如果都沒有找到,則會按預設配置輸出,也就是輸出到控制檯,也可以對配置檔案自定義位置(需要在web.xml中配置),一般放置在src/main/resources根目錄下即可。

以上就是小編給大家整理的全部相關知識點,感謝大家的學習。