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
相关推荐
Vitalia2 小时前
从零开始学Rust:枚举(enum)与模式匹配核心机制
开发语言·后端·rust
飞飞翼2 小时前
python-flask
后端·python·flask
草捏子4 小时前
最终一致性避坑指南:小白也能看懂的分布式系统生存法则
后端
一个public的class4 小时前
什么是 Java 泛型
java·开发语言·后端
清风絮柳4 小时前
51. “闲转易”交易平台小程序(基于springboot&vue)
vue.js·spring boot·小程序·毕业设计·校园二手交易平台·二手交易小程序·闲转易交易系统
头孢头孢5 小时前
k8s常用总结
运维·后端·k8s
TheITSea5 小时前
后端开发 SpringBoot 工程模板
spring boot·后端
Asthenia04125 小时前
编译原理中的词法分析器:从文本到符号的桥梁
后端
Asthenia04126 小时前
用RocketMQ和MyBatis实现下单-减库存-扣钱的事务一致性
后端
Pasregret6 小时前
04-深入解析 Spring 事务管理原理及源码
java·数据库·后端·spring·oracle