Spring Boot 如何配置 log4j2

Log4j2 介绍

Spring Boot 中默认使用 Logback 作为日志框架,接下来我们将学习如何在 Spring Boot 中集成与配置 Log4j2。在配置之前,我们需要知道的是 Log4j2 是 Log4j 的升级版,它在 Log4j 的基础上做了诸多改进:

  • 异步日志;
  • 支持 Java8 lambda 风格的懒加载日志;
  • 过滤器;
  • 插件;
  • 并发性改进;
  • 支持: SLF4J, Commons Logging, Log4j-1.x 以及 java.util.logging;
  • 配置热加载;
  • 自定义日志级别;

看到上面这些新特性,我们肯定特别想在我们的 Spring Boot 应用中使用 Log4j2

添加 Maven 依赖

Spring Boot 默认使用的是 logback, 想要使用 Log4j2, 我们需要首先排除掉默认的日志框架,然后添加 log4j2 依赖,下面是 pom.xml 文件:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId> 
</dependency>

添加 Log4j2 配置文件

Spring Boot 支持以下 4 种格式的配置文件:

  • xml(默认的)
  • json
  • yaml
  • properties 文件

Spring Boot 如果在 classpath:目录下找到了 log4j2.xml 或者 log4j2.json 或者 log4j2.properties或者log4j2.yaml的其中任意一个配置文件,就会自动加载并使用它。

接下来,我们来看看 log4j2.xml 格式,要如何配置?

在 /src/main/resource 目录下创建 log4j2.xml 配置文件:

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="PID">????</Property>
        <Property name="LOG_PATTERN">%clr{%d{yyyy-MM-dd HH:mm:ss.SSS}}{faint} %clr{%5p} %clr{${sys:PID}}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n%xwEx</Property>
    </Properties>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

彩蛋

点击下方链接,免费获取数千本电子书
免费获取

相关推荐
MC丶科15 小时前
【SpringBoot常见报错与解决方案】中文乱码?Spring Boot 统一解决前后端中文乱码问题(含 Postman 测试)!别再百度“加 UTF-8”了!
spring boot·后端·postman
XXOOXRT19 小时前
基于SpringBoot的加法计算器
java·spring boot·后端·html5
Coder_Boy_1 天前
基于SpringAI的在线考试系统-DDD业务领域模块设计思路
java·数据库·人工智能·spring boot·ddd
Voyager_41 天前
StringRedisTemplate 和 RedisTemplate 的区别是什么?
java·spring boot
小北方城市网1 天前
SpringBoot 全局异常处理与接口规范实战:打造健壮可维护接口
java·spring boot·redis·后端·python·spring·缓存
Chan161 天前
【 微服务SpringCloud | 方案设计 】
java·spring boot·微服务·云原生·架构·intellij-idea
hanqunfeng1 天前
(三十三)Redisson 实战
java·spring boot·后端
计算机毕设指导61 天前
基于微信小程序的运动场馆服务系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·intellij-idea
小北方城市网1 天前
SpringBoot 集成 MyBatis-Plus 实战(高效 CRUD 与复杂查询):简化数据库操作
java·数据库·人工智能·spring boot·后端·安全·mybatis
2401_861277551 天前
事件驱动架构软件测试要点是什么
单元测试·测试用例