# 4.日志配置-logback和log4j2

支持日志框架：Java Util Logging, Log4J2 and Logback，默认是使用logback

两种配置方式：**默认配置文件配置**和**引用外部配置文件配置(推荐)**

## 一、默认配置文件配置(不建议使用：不够灵活，对log4j2等不够友好)

```
# 日志文件名，比如：demo.log，或者是 /var/log/demo.log
logging.file=demo.log 
#logging.path=
# 日志级别配置，比如：`logging.level.org.springframework=DEBUG`
logging.level.*=info
logging.level.org.springframework=DEBUG
```

## 二、引用外部配置文件

**2.1 logback配置方式：**&#x20;

spring boot默认会加载`classpath:logback-spring.xml`或者`classpath:logback-spring.groovy`

使用自定义配置文件，配置方式为：

`logging.config=classpath:logback-demo.xml`

注意：不要使用logback这个来命名，否则spring boot将不能完全实例化

* 1.使用基于spring boot的配置

```
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    <logger name="org.springframework.web" level="DEBUG"/>
</configuration>
```

* 2.自定义配置

src/main/resources/下的 application.properties 加入如下配置

```
#主配置文件，配置了这个会优先读取里面的属性覆盖主配置文件的属性
spring.profiles.active=dev
# 应用自定义配置
logging.config=classpath:logback-demo.xml
```

src/main/resources/下的添加文件logback-demo.xml

```markup
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <!-- 文件输出格式 -->
    <property name="PATTERN" value="%-12(%d{yyyy-MM-dd HH:mm:ss.SSS}) |-%-5level [%thread] %c [%L] -| %msg%n" />
    <!-- test文件路径 -->
    <property name="TEST_FILE_PATH" value="c:/opt/demo/logs" />
    <!-- pro文件路径 -->
    <property name="PRO_FILE_PATH" value="/opt/demo/logs" />

    <!-- 开发环境 -->
    <springProfile name="dev">
        <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>${PATTERN}</pattern>
            </encoder>
        </appender>

        <logger name="com.shuju.example" level="debug"/>

        <root level="info">
            <appender-ref ref="CONSOLE" />
        </root>
    </springProfile>

    <!-- 测试环境 -->
    <springProfile name="test">
        <!-- 每天产生一个文件 -->
        <appender name="TEST-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <!-- 文件路径 -->
            <file>${TEST_FILE_PATH}</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <!-- 文件名称 -->
                <fileNamePattern>${TEST_FILE_PATH}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
                <!-- 文件最大保存历史数量 -->
                <MaxHistory>100</MaxHistory>
            </rollingPolicy>

            <layout class="ch.qos.logback.classic.PatternLayout">
                <pattern>${PATTERN}</pattern>
            </layout>
        </appender>

        <root level="info">
            <appender-ref ref="TEST-FILE" />
        </root>
    </springProfile>

    <!-- 生产环境 -->
    <springProfile name="prod">
        <appender name="PROD_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${PRO_FILE_PATH}</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${PRO_FILE_PATH}/warn.%d{yyyy-MM-dd}.log</fileNamePattern>
                <MaxHistory>100</MaxHistory>
            </rollingPolicy>
            <layout class="ch.qos.logback.classic.PatternLayout">
                <pattern>${PATTERN}</pattern>
            </layout>
        </appender>

        <root level="warn">
            <appender-ref ref="PROD_FILE" />
        </root>
    </springProfile>
</configuration>
```

其中name=“dev” 都是启动不同环境的日志配置

> 附录
>
> application-dev.properties
>
> ```
> #开发环境
> server.port=8080
> ```
>
> application-prod.properties
>
> ```
> #生产环境
> server.port=8082
> ```
>
> application-test.properties
>
> ```
> #测试环境
> server.port=8081
> ```

![](/files/-LfnTI38VUjVQHmcvOCK)

> 附录参考
>
> ```markup
> <?xml version="1.0" encoding="UTF-8"?>
> <configuration debug="false">
>
>     <!--只在非生产环境往控制台打印日志 -->
>     <springProfile name="pro">
>         <property name="TO_CONSOLE" value="false" />
>     </springProfile>
>     <springProfile name="!pro">
>         <property name="TO_CONSOLE" value="true" />
>     </springProfile>
>
>     <!-- 控制台输出 -->
>     <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
>         <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
>             <!--格式化输出：%d表示日期，%thread表示线程名，%-5level：级别从左显示5个字符宽度%msg：日志消息，%n是换行符 -->
>             <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%line - %msg%n</pattern>
>             <charset>UTF-8</charset>
>         </encoder>
>     </appender>
>
>     <!-- 按照每天生成日志文件 -->
>     <appender name="FILE"
>         class="ch.qos.logback.core.rolling.RollingFileAppender">
>         <file>${LOG_PATH}/${LOG_FILE}.log</file>
>         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
>             <!-- rollover daily -->
>             <fileNamePattern>${LOG_PATH}/${LOG_FILE}-%d{yyyy-MM-dd}.%i.log
>             </fileNamePattern>
>             <timeBasedFileNamingAndTriggeringPolicy
>                 class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
>                 <!-- or whenever the file size reaches 100MB -->
>                 <maxFileSize>100MB</maxFileSize>
>             </timeBasedFileNamingAndTriggeringPolicy>
>         </rollingPolicy>
>         <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
>             <!--格式化输出：%d表示日期，%thread表示线程名，%-5level：级别从左显示5个字符宽度%msg：日志消息，%n是换行符 -->
>             <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%line - %msg%n</pattern>
>             <charset>UTF-8</charset>
>         </encoder>
>     </appender>
>
>     <!-- 日志输出级别 -->
>     <root level="INFO">
>         <appender-ref ref="STDOUT" />
>     </root>
>
>     <logger name="com" level="INFO" additivity="${TO_CONSOLE}">
>         <appender-ref ref="FILE"/>
>     </logger>
>     
>     <logger name="org" level="INFO" additivity="${TO_CONSOLE}">
>         <appender-ref ref="FILE"/>
>     </logger>
>
> </configuration>
> ```

**2.2 log4j配置**

* 2.2.1去除logback的依赖包，添加log4j2的依赖包

```markup
<exclusions>
    <exclusion>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
</exclusions>
```

按照如下配置 ：

```markup
<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>
<!-- 使用log4j2 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
```

* 2.2.2 在classpath添加log4j2.xml或者log4j2-spring.xml（spring boot 默认会自动加载配置的xml）
* 2.3 自定义配置文件

src/main/resources/下的 application-dev.properties 加入如下配置

```markup
#应用自定义配置
logging.config=classpath:log4j2-dev.xml
```

test 和prod效仿即可

![](/files/-LfnTI3CSn0mJtahOC-p)

src/main/resources/下的添加文件log4j2-dev.xml

```markup
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <properties>
        <!-- 文件输出格式 -->
        <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} |-%-5level [%thread] %c [%L] -| %msg%n</property>
    </properties>

    <appenders>
        <Console name="CONSOLE" target="system_out">
            <PatternLayout pattern="${PATTERN}" />
        </Console>
    </appenders>

    <loggers>
        <logger name="com.shuju.example" level="debug" />
        <root level="info">
            <appenderref ref="CONSOLE" />
        </root>
    </loggers>

</configuration>
```

## 三．比较

性能比较：Log4J2 和 Logback 都优于 log4j（不推荐使用）

配置方式：Logback最简洁，spring boot默认，推荐使用

## 资料

[在SpringBoot项目中添加logback的MDC](https://blog.csdn.net/hongyang321/article/details/78803584) - 将用户信息打入log的方案

[Spring Boot 日志记录 SLF4J](https://blog.csdn.net/catoop/article/details/50501714)

```java
// 在Java类中创建 logger 实例
private static final Logger logger = LoggerFactory.getLogger(SpringBootSampleApplication.class);
// 在方法中使用日志输出，如
public void logTest() {
    logger.debug("日志输出测试 Debug");
    logger.trace("日志输出测试 Trace");
    logger.info("日志输出测试 Info");
}
```

[使用SLF4J和Logback](https://www.liaoxuefeng.com/wiki/1252599548343744/1264739155914176)

logback相当于是一个日志系统,SLF4J相当于是一个在其之上封装了一层日志接口,用于简化使用.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://spring-boot.shujuwajue.com/ji-chu-jiao-cheng/ri-zhi-pei-7f6e-logback-he-log4j2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
