Spring Boot Log4j2属性示例

Spring Boot的默认日志记录使用Logback作为传递依赖项。如果Spring Boot在类路径上,则支持Log4j2进行日志记录配置。

使用Spring Boot配置Log4j2,请遵循以下两个简单步骤:

1.添加Log4j2 Maven依赖关系

实际上,这是两个步骤的改变。首先删除spring的默认日志记录依赖项(spring-boot-starter-logging),然后添加log4j2依赖项(spring-boot-starter-log4j2)。

一旦在类路径中找到了jar文件,Spring就会自动配置log4j2。

pom.xml
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
</parent>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <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>
</dependencies>

2.在资源文件夹中添加log4j2属性文件

现在我们必须在文件夹中添加log4j2.properties或(log4j2.xmlsrc/main/resources。就这样。

log4j2。属性
status = error
name = PropertiesConfig
filters = threshold
filter.threshold.type = ThresholdFilter
filter.threshold.level = debug
appenders = console
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

阅读更多:Log4j2属性文件示例

3. Spring Boot log4j2属性记录示例

现在在应用程序中添加一些日志语句,并查看已配置的附加程序中的日志,例如我配置的控制台和文件。

应用程序
package com.how2codex.app;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    private static final Logger LOGGER = LogManager.getLogger(Application.class);
    public static void main(String[] args)
    {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        
        LOGGER.info("Info level log message");
        LOGGER.debug("Debug level log message");
        LOGGER.error("Error level log message");
    }
}

检查输出。

记录输出
2018-06-01T13:55:42.506+0530 INFO Info level log message
2018-06-01T13:55:42.506+0530 DEBUG Debug level log message
2018-06-01T13:55:42.506+0530 ERROR Error level log message

如果您对spring boot log4j

saigon has written 1440 articles

Leave a Reply