Spring Boot 支持哪些日志框架

Spring Boot 支持多种日志框架,主要包括以下几种:

  1. SLF4J (Simple Logging Facade for Java) + Logback(默认)
  2. Log4j 2
  3. Java Util Logging (JUL)

其中,Spring Boot 默认使用 SLF4JLogback 作为日志框架。如果你需要使用其他日志框架(如 Log4j 2),可以通过添加相关依赖和配置来替代默认的 Logback。

下面将分别介绍如何在 Spring Boot 中使用不同的日志框架,并给出相应的示例代码。

1. 默认日志框架:SLF4J + Logback

Spring Boot 默认集成了 SLF4JLogback,因此你无需添加额外的依赖,只需要在代码中使用 SLF4J API 即可。

示例代码:
java 复制代码
package com.hk.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    public void registerUser(String username) {
        logger.debug("Debug: Starting user reg for {}", username);
        try {
            if (!StringUtils.hasText(username)) {
                logger.error("Error: Username 不能为null");
                throw new IllegalArgumentException("Username 不能为null");
            }
            logger.info("Info: User {} reg successfully", username);
        } catch (Exception e) {
            logger.error("Error: User registration failed for {}", username, e);
        }
    }
}
配置日志级别(application.yml):
yaml 复制代码
logging:
    file:
        name: logs/application.log   # 配置日志文件
    level:
        com:
            hk: DEBUG                # 设置特定包的日志级别
        root: INFO                   # 设置根日志级别为 INFO

2. 使用 Log4j 2 作为日志框

如果你希望使用 Log4j 2 代替 Logback,可以按照以下步骤操作:

步骤 1:添加 Log4j 2 依赖

首先,你需要在 pom.xml 中排除默认的 Logback 依赖并添加 Log4j 2 的依赖。

xml 复制代码
<dependencies>
    <!-- 排除默认的 Logback 依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
        <scope>provided</scope>
    </dependency>

    <!-- 添加 Log4j 2 依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
</dependencies>
步骤 2:创建 Log4j 2 配置文件(log4j2.xml

src/main/resources/ 目录下创建 log4j2.xml 文件,配置 Log4j 2 的日志输出格式和日志级别。

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <!-- 配置 Console Appender 输出 -->
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout>
                <Pattern>%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n</Pattern>
            </PatternLayout>
        </Console>
    </Appenders>

    <!-- 配置 Logger -->
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>
步骤 3:使用 Log4j 2 记录日志

Log4j 2 同样支持 SLF4J 接口,因此在代码中不需要做特别的修改,依然可以使用 SLF4J API 记录日志。

java 复制代码
package com.hk.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    public void registerUser(String username) {
        logger.debug("Debug: Starting user reg for {}", username);
        try {
            if (!StringUtils.hasText(username)) {
                logger.error("Error: Username 不能为null");
                throw new IllegalArgumentException("Username 不能为null");
            }
            logger.info("Info: User {} reg successfully", username);
        } catch (Exception e) {
            logger.error("Error: User registration failed for {}", username, e);
        }
    }
}

3. 使用 Java Util Logging (JUL)

如果你想使用 Java Util Logging (JUL),你可以通过以下方式进行配置:

步骤 1:排除默认的 Logback 依赖

和 Log4j 2 一样,需要排除默认的 Logback 依赖。

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
    <scope>provided</scope>
</dependency>
步骤 2:配置 application.yml
yaml 复制代码
logging:
    file:
        name: logs/application.log   # 配置日志文件
    level:
        root: INFO                   # 设置根日志级别为 INFO
步骤 3:使用 JUL 记录日志

需要简单的修改代码

java 复制代码
package com.hk.service;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.logging.Logger;

@Service
public class UserService {

    private static final Logger logger = Logger.getLogger(UserService.class.getName());

    public void registerUser(String username) {
        logger.fine("Debug: Starting user reg for" +  username);
        try {
            if (!StringUtils.hasText(username)) {
                logger.severe("Error: Username 不能为null");
                throw new IllegalArgumentException("Username 不能为null");
            }
            logger.info("Info: User " +username +"reg successfully");
        } catch (Exception e) {
            logger.severe("Error: User registration failed for" + username);
            e.printStackTrace();
        }
    }
}

总结

Spring Boot 支持多种日志框架,并且允许你轻松切换这些框架:

  • 默认使用 SLF4JLogback,无需额外配置。
  • 使用 Log4j 2 时,需要排除默认的 Logback 并添加 Log4j 2 依赖和配置。
  • 使用 Java Util Logging (JUL) 时,配置日志级别并使用 java.util.logging.Logger
相关推荐
chxii42 分钟前
Spring Boot 响应给客户端的常见返回类型
java·spring boot·后端
韩立学长44 分钟前
【开题答辩实录分享】以《植物爱好者交流平台的设计与实现》为例进行答辩实录分享
spring boot·后端·mysql
Wzx1980121 小时前
go基础语法练习
开发语言·后端·golang
sp421 小时前
漫谈 Java 轻量级的模板技术:从字符串替换到复杂模板
java·后端
2301_795167201 小时前
玩转Rust高级应用. ToOwned trait 提供的是一种更“泛化”的Clone 的功能,Clone一般是从&T类型变量创造一个新的T类型变量
开发语言·后端·rust
慧都小项1 小时前
Parasoft C/C++test如何使用桩函数替代MFC窗口类顺利执行单元测试
单元测试·parasoft·桩函数·mfc窗口类
草莓熊Lotso2 小时前
C++ 方向 Web 自动化测试实战:以博客系统为例,从用例到报告全流程解析
前端·网络·c++·人工智能·后端·python·功能测试
一 乐2 小时前
旅游|内蒙古景点旅游|基于Springboot+Vue的内蒙古景点旅游管理系统设计与实现(源码+数据库+文档)
开发语言·前端·数据库·vue.js·spring boot·后端·旅游
JaguarJack2 小时前
15 个 Eloquent 高级技巧,瞬间提升你的 Laravel 应用性能
后端·php·laravel
YDS8292 小时前
苍穹外卖 —— Spring Cache和购物车功能开发
java·spring boot·后端·spring·mybatis