当前位置: 首页 > news >正文

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 文件:

<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 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>
http://www.lryc.cn/news/262132.html

相关文章:

  • 如何安装docker
  • Linux 之 性能优化
  • 用Go汇编实现一个快速排序算法
  • Spring-整合MyBatis
  • sql宽字节注入
  • 开源 LLM 微调训练指南:如何打造属于自己的 LLM 模型
  • Android hilt使用
  • 2023/12/17 初始化
  • 【算法Hot100系列】三数之和
  • CSS 简介
  • myBatis-plus自动填充插件
  • 746. 使用最小花费爬楼梯 --力扣 --JAVA
  • 使用Verdaccio搭建私有npm仓库
  • 87 GB 模型种子,GPT-4 缩小版,超越ChatGPT3.5,多平台在线体验
  • Golang 数组 移除元素 双指针法 leetcode27 小记
  • c# OpenCV 图像裁剪、调整大小、旋转、透视(三)
  • Kafka相关知识
  • gitlab 通过svn hook 触发
  • 设计模式详解---单例模式
  • 毕设之-Hlang后端架构-双系统交互
  • 什么同源策略?
  • 破译模式:模式识别在计算机视觉中的作用
  • c语言-全局变量与局部变量
  • 【Spring】00 入门指南
  • BIM 技术:CIM (City Information Modeling) 1-7 级
  • c++ websocket 协议分析与实现
  • kali虚拟机无网络
  • Unity2023.3(Unity6)版本开始将可以发布WebGPU
  • 计算机网络期末考试A卷及答案
  • <蓝桥杯软件赛>零基础备赛20周--第10周--二分