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
相关推荐
BS30813_vx几秒前
基于 Express + uni-app 的养老院管理系统设计与实现
后端·uni-app·express
明月_清风11 分钟前
DeepSeek Harness 安全审计实录:四个 PoC 揭露的 Agent 运行时"信任危机"
后端·安全·agent
苏三说技术25 分钟前
再见了EasyExcel,我决定用Apache Fesod
后端
XR12345678838 分钟前
医院移动医护零漫游无线网络选型指南
java·后端·struts
慧一居士1 小时前
Mybatis Plus中 LambdaQueryWrapper、QueryWrapper 区别对比
spring boot
干到60岁退休的码农1 小时前
13.构建登录接口响应数据
java·spring boot·mybatis
水巷石子1 小时前
学习langChain4j的第二天,体验springBoot中的starter
java·spring boot·学习·spring·langchain4j
ly76891 小时前
Spring Bean生命周期全流程:从BeanDefinition到销毁
java·后端·spring·bean生命周期·beandefinition·初始化回调
leeyi1 小时前
在 Go 里跑不信任的代码:WASM 沙箱的四道墙(第107篇)
后端
摇滚侠1 小时前
《Spring Boot 3:高级与架构设计》第 1 章 BeanDefinitionRegistry 阅读笔记 3
spring boot·笔记·后端