SpringBoot-使用log4j2日志配置

前言

  • Apache Log4j2 是对 Log4j 的升级,它比其前身 Log4j 1.x 提供了重大改进,并提供了 Logback 中可用的许多改进,同时修复了 Logback 的 architecture 中的一些固有问题。
  • Spring Boot 默认使用 logback,但相比较而言,log4j2 在性能上面会更好。SpringBoot 高版本都不再支持 log4j,而是支持 log4j2。log4j2 在使用方面与 log4j 基本上没什么区别,比较大的区别是 log4j2 不再支持 properties 配置文件,支持 xml、json、xml格式的文件。

pom.xml文件

disruptor为log4j2 异步依赖,可根据自己的需求自行配置,本文未使用。同时这里也使用了lombok。下面有例子。

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
            
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-starter-loggingartifactId>
                exclusion>
            exclusions>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-log4j2artifactId>
        dependency>

        
        <dependency>
            <groupId>com.lmaxgroupId>
            <artifactId>disruptorartifactId>
            <version>3.4.2version>
        dependency>

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

log4j2配置文件

log4j2异步配置已注释,需要的可自行配置。具体配置详解可以参考log4j2配置全解



<Configuration status="info">

    
    <Properties>
        <Property name="fileName">logs/spring-boot-log4j2Property>
        <Property name="fileGz">logs/spring-boot-log4j2/7zProperty>
        <property name="PATTERN">%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%nproperty>
    Properties>

    <Appenders>

        
        <Console name="console" target="SYSTEM_OUT">
            
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            
            <PatternLayout pattern="${PATTERN}" charset="UTF-8"/>
        Console>

        
        
        <RollingRandomAccessFile name="infoFile" fileName="${fileName}/log-info.log" immediateFlush="true"
                                 filePattern="${fileGz}/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.web-info.gz">
            <PatternLayout pattern="${PATTERN}" charset="UTF-8"/>

            <Policies>
                <TimeBasedTriggeringPolicy interval="6" modulate="true"/>
                <SizeBasedTriggeringPolicy size="50 MB"/>
            Policies>

            <Filters>
                
                <ThresholdFilter level="error" onMatch="DENY" onMismatch="NEUTRAL"/>
                <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            Filters>

            
            <DefaultRolloverStrategy max="50"/>
        RollingRandomAccessFile>

        
        <RollingRandomAccessFile name="errorFile" fileName="${fileName}/log-error.log" immediateFlush="true"
                                 filePattern="${fileGz}/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.web-error.gz">
            <PatternLayout pattern="${PATTERN}" charset="UTF-8"/>

            <Policies>
                <TimeBasedTriggeringPolicy interval="6" modulate="true"/>
                <SizeBasedTriggeringPolicy size="50 MB"/>
            Policies>

            <Filters>
                
                <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            Filters>

            
            <DefaultRolloverStrategy max="50"/>
        RollingRandomAccessFile>
    Appenders>

    
    <Loggers>
        
        
        
        <Root level="info">
            <AppenderRef ref="console"/>
            <AppenderRef ref="infoFile"/>
            <AppenderRef ref="errorFile"/>
        Root>
        
        <logger name="org.springframework" level="info" additivity="true">
        logger>

        
        
        
        
        
        
    Loggers>
Configuration>

controller类

  • 未使用lombok。
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {

    private static final Logger logger = LogManager.getLogger(IndexController.class);

    @RequestMapping("/index")
    public String index() {
        logger.debug("记录debug日志............");
        logger.info("访问了index方法............");
        logger.warn("访问了warn方法............");
        logger.error("记录了error错误日志............");
        logger.fatal("访问了fatal方法............");

        try {
            int i = 0;
            int j = 1 / i;
        } catch (Exception e) {
            logger.error("错误异常............:", e);
        }
        return "index";
    }
}
  • 使用lombok。
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Log4j2
public class IndexController2 {

    @RequestMapping("/index2")
    public String index2() {

        log.debug("记录debug日志");
        log.info("访问了index方法");
        log.warn("访问了warn方法");
        log.error("记录了error错误日志");
        log.fatal("访问了fatal方法");

        try {
            int i = 0;
            int j = 1 / i;
        } catch (Exception e) {
            log.error("错误异常:", e);
        }
        return "index2";
    }
}

你可能感兴趣的:(Spring,spring,boot,java,spring)