log4j在Spring Boot中的应用

发布时间:2025-02-16 15:42:55 作者:小樊
来源:亿速云 阅读:113

在Spring Boot中使用Log4j2作为日志记录框架是一个相对简单的过程。以下是详细的步骤和注意事项:

1. 排除默认的日志依赖

首先,需要在项目的pom.xml文件中排除默认的Logback依赖,并添加Log4j2的依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

2. 创建Log4j2配置文件

src/main/resources目录下创建log4j2.xml文件,并进行相应的配置。

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <RollingFile name="RollingFile" fileName="logs/app.log" filePattern="logs/app-%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="RollingFile"/>
        </Root>
    </Loggers>
</Configuration>

3. 配置文件的优先级

确保Log4j2配置文件的优先级正确。Spring Boot会按照以下顺序查找配置文件:

  1. classpath下的log4j2-test.jsonlog4j2-test.jsn文件。
  2. classpath下的log4j2-test.xml文件。
  3. classpath下名为log4j2.jsonlog4j2.jsn的文件。
  4. classpath下名为log4j2.xml的文件。

4. 使用Log4j2

在代码中使用Log4j2进行日志记录。

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class MyClass {
    private static final Logger logger = LogManager.getLogger(MyClass.class);

    public static void main(String[] args) {
        logger.debug("This is a debug message");
        logger.info("This is an info message");
        logger.warn("This is a warning message");
        logger.error("This is an error message");
    }
}

5. 注意事项

通过以上步骤,您可以在Spring Boot项目中成功集成和使用Log4j2作为日志记录框架。

推荐阅读:
  1. SpringBoot使用Log4j过程详解
  2. SpringBoot使用Log4j的知识点整理

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:如何使用log4j进行远程日志记录

下一篇:Apache log4j的API使用教程

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》