Spring Boot 支持哪些日志框架

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

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

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

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

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

Spring Boot 默认集成了 SLF4J 和 Logback,因此你无需添加额外的依赖,只需要在代码中使用 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 支持多种日志框架,并且允许你轻松切换这些框架:

  • 默认使用 SLF4J 和 Logback,无需额外配置。
  • 使用 Log4j 2 时,需要排除默认的 Logback 并添加 Log4j 2 依赖和配置。
  • 使用 Java Util Logging (JUL) 时,配置日志级别并使用 java.util.logging.Logger
相关推荐
FYKJ_20106 小时前
springboot高校实验室综合管理系统86531-计算机毕业设计、课程设计
java·vue.js·spring boot·后端·python·spring·课程设计
parade岁月7 小时前
没有称手工具了怎么办?搓一个!AI 时代顺手造了个单文件 Mermaid ER 查看器
数据库·后端
金銀銅鐵12 小时前
类实例里还有什么——putfield、getfield 与对象传递
java·jvm·后端
织码weavecodes12 小时前
Spring Boot 接入 AI 图像生成:模型适配、图片转存与 Redis 清理
人工智能·spring boot·redis
皮皮林55113 小时前
你还在使用 WebSocket 实现实时消息推送吗?
后端
码事漫谈14 小时前
token账单到底要怎么看
后端
Cosolar14 小时前
当 Harness 标准化后,工程师还剩什么?
人工智能·后端·agent
打工仔折腾 AI15 小时前
L3 静态源码取证|工程评测:python-oracledb 驱动评估中的样本偏差陷阱
开发语言·人工智能·后端·python·性能优化
stark张宇15 小时前
分布式事务方案设计与选型思考:消息队列
后端
想不到一个好的ID16 小时前
什么是线程安全
后端