问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Spring Boot 支持哪些日志框架

创作时间:
作者:
@小白创作中心

Spring Boot 支持哪些日志框架

引用
CSDN
1.
https://m.blog.csdn.net/hekai7217/article/details/145073842

Spring Boot作为广受欢迎的Java开发框架,其日志系统配置是开发者必须掌握的重要技能。本文将详细介绍Spring Boot支持的主要日志框架及其配置方法,包括默认的SLF4J+Logback组合,以及如何切换到Log4j 2或Java Util Logging (JUL)。通过本文,你将能够根据项目需求灵活选择和配置合适日志框架。

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 中使用不同的日志框架,并给出相应的示例代码。

默认日志框架:SLF4J + Logback

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

示例代码:

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):

logging:
    file:
        name: logs/application.log   # 配置日志文件
    level:
        com:
            hk: DEBUG                # 设置特定包的日志级别
        root: INFO                   # 设置根日志级别为 INFO

使用 Log4j 2 作为日志框架

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

步骤 1:添加 Log4j 2 依赖

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

<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 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 记录日志。

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);
        }
    }
}

使用 Java Util Logging (JUL)

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

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

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
    <scope>provided</scope>
</dependency>

步骤 2:配置 application.yml

logging:
    file:
        name: logs/application.log   # 配置日志文件
    level:
        root: INFO                   # 设置根日志级别为 INFO

步骤 3:使用 JUL 记录日志

需要简单的修改代码

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
© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号