1. 程式人生 > >spring boot配置log4j2日誌問題

spring boot配置log4j2日誌問題

第一步:配置log4j2.xml resources目錄下新建該檔案

<?xml version="1.0" encoding="utf-8"?>
<!--日誌級別:TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果設定為WARN,則低於WARN的資訊都不會輸出-->
<!--
    status : 這個用於設定log4j2自身內部的資訊輸出,可以不設定,當設定成trace時,會看到log4j2內部各種詳細輸出
    monitorInterval : Log4j能夠自動檢測修改配置檔案和重新配置本身, 設定間隔秒數。此處表示每隔300秒重讀一次配置檔案
-->
<Configuration status="info" monitorInterval="300">
    <!--<properties>-->
    <!--<property name="LOG_HOME">F:\logs</property>-->
    <!--<property name="ERROR_LOG_FILE_NAME">error</property>-->
    <!--</properties>-->
    <Properties>
        <Property name="log_path">logs</Property><!-- 這裡的logs為專案根目錄下的logs資料夾 -->
        <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        <!-- 高亮控制檯輸出  -->
        <Property name="log_pattern_highlight">%highlight{${log_pattern}}{FATAL=Bright Red, ERROR=Magenta, WARN=Cyan, INFO=Green, DEBUG=Yellow, TRACE=Bright Blue}</Property>
    </Properties>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT"> <!-- 定義型別為Console的Appender -->
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </Console>
    </Appenders>
    <!--定義logger,只有定義了logger並引入上面的appender,appender才會生效-->
    <Loggers>
        <Root level="info"> <!-- 定義Root Logger -->
            <AppenderRef ref="Console"/> <!-- Root Logger的Appender引用上面定義的Console -->
        </Root>
        <!--定義名字為MainLogger的Logger,其日誌級別為info,info以下級別的資訊將不會輸出 -->
        <Logger name="MainLogger" level="info" additivity="false">
            <AppenderRef ref="Console"/> <!-- Root Logger的Appender引用上面定義的Console -->
        </Logger>
    </Loggers>
</Configuration>

以上配置列印的日誌會帶行號連線點選連線會跳轉到具體行

第二部: 引入依賴,pom.xml中新增


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

第三步:排除依賴,使用exclusion標籤排除Logback,具體程式碼如下

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <!--排除spring boot 預設日誌-->
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

第四步 新增log4j2配置


spring:
  profiles:
    active: dev
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=utf-8
    username: root
    password: ****
  jpa:
    hibernate:
      ddl-auto: update
      dialect: mysql
    show-sql: true

  logging:
#    config: logback.xml   
    config: log4j2.xml
    level:
      com.mb: debug

spring: 空格logging: 空格空格config: log4j2.xml 最終效果 在這裡插入圖片描述