springboot 使用 log4j2 进行日志记录、并对文件日志以日期和大小进行拆分的 demo 示例

本文介绍了一个SpringBoot项目如何使用Log4j2进行日志记录,包括配置控制台日志输出、文件日志输出及日志文件按日期和大小进行归档的方法。

1. 描述

一个springboot项目使用 log4j2 记录程序运行过程中的日志, 配置 log4j2 生成控制台日志和文件日志记录,以及对文件日志以日期和大小进行拆分的 demo示例。

环境:

IDE(idea)2021.3
JDK:1.8
maven:3.8.4
spring boot:2.5.6 
log4j-core: 2.14.1 (spring-boot-starter-log4j2: 2.56)

提示:

写这个demo的过程中遇到不少问题(写在最后)。 文档和源码都看得我有点懵,感觉比 logback 的上手难度大不少。

2. 结果

  • 控制台日志格式:
    在这里插入图片描述
  • 文件日志格式:
    在这里插入图片描述
  • 日志拆分归档:eg: 日志文件最大10KB,总文件大小20KB,最长时间30天, 当前策略目录下总文件格式19, 满足条件的总文件数20(Delete配置,不止针对当前策略)
    在这里插入图片描述
    在这里插入图片描述

3. demo

用了个定时任务在打印日志, 输出的日志文件用zip压缩格式进行了归档。文件大小设置的较小,以便于测试。

3.0 项目结构
在这里插入图片描述

3.1 pom.xml

  • 引入 log4j2 相关jar包(排除出web依赖中已有logging依赖)。
		<!--提供全栈的 web 开发特性,包括 Spring MVC 依赖和 Tomcat 容器-->
        <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>
        <!-- Required for AsyncLoggers -->
        <dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <version>3.4.4</version>
        </dependency>

3.2 SpringBootApplication

  • 使用了EnableScheduling 注解,启用定时任务。
@Slf4j
@EnableScheduling // 启用定时任务
@SpringBootApplication
public class DemoLogLog4j2Application {
   
   
    public static void main(String[] args) {
   
   
        ConfigurableEnvironment environment = SpringApplication.run(DemoLogLog4j2Application.class, args).getEnvironment();
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值