欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot中log4j的配置

程序员文章站 2022-03-02 14:37:37
...

上篇文章Spring Boot日志管理,我简单讲述了Spring Boot中使用默认日志Logback进行日志管理的配置。在上篇文章中有讲到,LogBack是Log4j的改良版本,比Log4j拥有更多的特性,同时也带来很大性能提升。但是log4j作为一款常用的日志库,在实际开发中还是很常用的,本片文章,我将简单介绍一下Spring Boot中如何使用Log4J进行日志管理。

创建Spring Boot工程时,必然会引入了spring-boot-starter,其中包含了spring-boot-starter-logging,该依赖内容就是Spring Boot默认的日志框架Logback,所以我们在引入log4j之前,首先要先排除该包的依赖,再引入log4j的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</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>

在src/main/resuorces文件夹添加log4j配置文件log4j2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">
            %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
        </Property>
    </Properties>
    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="com.example.log4j2demo" level="debug" additivity="false">
            <AppenderRef ref="ConsoleAppender"/>
        </Logger>

        <Root level="info">
            <AppenderRef ref="ConsoleAppender"/>
        </Root>
    </Loggers>
</Configuration>

log4J也可以和SLF4J配合使用,实现运行时绑定log4J实例,使用方法与上一篇文章logback一致。

@RestController
@RequestMapping(value = "/health")
public class HealthCheckController {
    private final Logger logger = LoggerFactory.getLogger(Object.class);

    @RequestMapping(value = "/check", method = RequestMethod.GET)
    public String check(){
        logger.trace("health check controller trace……");
        logger.debug("health check controller debug……");
        logger.info("health check controller info……");
        logger.warn("health check controller warn……");
        logger.error("health check controller error……");
        return "ok";
    }
}
  • Log4j文件输出配置

在Logback中可以通过配置RollingFile子节点达到文件输出的目的,配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">
            %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
        </Property>
    </Properties>
    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>

        <RollingFile name="FileAppender" fileName="d:/log/log4j2-demo.log"
                     filePattern="d:/log/log4j2-demo-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout>
                <Pattern>${LOG_PATTERN}</Pattern>
            </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="10MB" />
            </Policies>
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Logger name="com.zhuoli.service.springboot.log4j" level="debug" additivity="false">
            <AppenderRef ref="ConsoleAppender" />
        </Logger>

        <Root level="info">
            <AppenderRef ref="ConsoleAppender" />
            <AppenderRef ref="FileAppender" />
        </Root>
    </Loggers>
</Configuration>
  • Log4j异步日志

log4j启动异步需要lmax支持,需要引入jar包:

<!-- Needed for Async Logging with Log4j 2 -->
<dependency>
    <groupId>com.lmax</groupId>
    <artifactId>disruptor</artifactId>
    <version>3.3.6</version>
</dependency>

修改日志输出为异步:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">
            %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
        </Property>
    </Properties>
    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>

        <RollingFile name="FileAppender" fileName="d:/log/log4j2-demo.log"
                     filePattern="d:/log/log4j2-demo-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout>
                <Pattern>${LOG_PATTERN}</Pattern>
            </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="10MB" />
            </Policies>
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>

        <!--file异步输出-->
        <Async name="AsyncFile" buffersize="32768" blocking="false">
            <AppenderRef ref="FileAppender"/>
        </Async>

        <!--console异步输出-->
        <Async name="AsyncConsole" buffersize="32768" blocking="false">
            <AppenderRef ref="ConsoleAppender"/>
        </Async>
    </Appenders>
    <Loggers>
        <Logger name="org.apache.catalina.startup.DigesterFactory" level="error"/>
        <Logger name="org.apache.catalina.util.LifecycleBase" level="error"/>
        <Logger name="org.apache.coyote.http11.Http11NioProtocol" level="warn"/>
        <logger name="org.apache.sshd.common.util.SecurityUtils" level="warn"/>
        <Logger name="org.apache.tomcat.util.net.NioSelectorPool" level="warn"/>
        <Logger name="org.crsh.plugin" level="warn"/>
        <logger name="org.crsh.ssh" level="warn"/>
        <Logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="error"/>
        <Logger name="org.hibernate.validator.internal.util.Version" level="warn"/>
        <logger name="org.springframework.boot.actuate.autoconfigure.CrshAutoConfiguration" level="warn"/>
        <logger name="org.springframework.boot.actuate.endpoint.jmx" level="warn"/>
        <logger name="org.thymeleaf" level="warn"/>
        <logger name="org.springframework.context.support" level="warn"/>
        <logger name="org.springframework.jmx.export.annotation" level="warn"/>
        <logger name="com.zaxxer.hikari" level="warn"/>
        <logger name="org.springframework.context.annotation.AnnotationConfigApplicationContext" level="warn"/>
        <logger name="org.springframework.web.servlet.mvc.method.annotation" level="warn"/>
        <logger name="metrics_influxdb.measurements" level="off"/>

        <Root level="info">
            <AppenderRef ref="AsyncConsole" />
            <AppenderRef ref="AsyncFile" />
        </Root>
    </Loggers>
</Configuration>

上述配置实现了日志异步输出,及区别包进行不同级别的log输出,在日常开发中基本是可用的。通过本片文章可以看出,其实log4j配置和logback配置是相通的,建议想了解日志配置的同学花时间去看一下上篇Spring Boot日志管理的文章。另外,在生产上,通过kafaka异步日志输出也是非常常见的,想了解的同学可以看一下这一篇文章Kafka+Log4j实现日志集中管理

示例代码:码云 – 卓立 – Spring Boot + log4j日志配置

相关标签: SpringBoot