spring boot start log4j2 開啓異步

springboot項目使用log4j2,正常引入如下依賴:java

<!-- Exclude Spring Boot's Default Logging 若是把logging移除了,idea打印的貌似就不是彩色的了。 -->
<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>

<!-- Add Log4j2 Dependency -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

spring若是掃描到有一個名字叫作log4j2.xml or log4j2.json or log4j2.yaml在classpath下,就會自動配置好了。spring

本文使用log4j2.xml格式文件,看下面最簡單的示例;apache

<?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>

在代碼中使用:json

package com.example.log4j2demo;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Log4j2DemoApplication implements ApplicationRunner {
    private static final Logger logger = LogManager.getLogger(Log4j2DemoApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(Log4j2DemoApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        logger.debug("Debugging log");
        logger.info("Info log");
        logger.warn("Hey, This is a warning!");
        logger.error("Oops! We have an Error. OK");
        logger.fatal("Damn! Fatal error. Please fix me.");
    }
}

若是項目有lombok庫的,能夠直接在類上聲明@Slf4jspringboot

,若是你想把log寫入log文件,就添加一個文件Appender:bash

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

在Root節點配置:app

<Root level="info">
    <AppenderRef ref="ConsoleAppender"/>
    <AppenderRef ref="FileAppender"/>
</Root>

添加使用發送郵件功能(自測一直沒有發送成功!):異步

<!-- SMTP Appender -->
<SMTP name="MailAppender"
      subject="Log4j2 Demo [PROD]"
      to="youremail@example.com"
      from="log4j2-demo-alerts@example.com"
      smtpHost="yourSMTPHost"
      smtpPort="587"
      smtpUsername="yourSMTPUsername"
      smtpPassword="yourSMTPPassword"
      bufferSize="1">
    <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
    <PatternLayout>
        <Pattern>${LOG_PATTERN}</Pattern>
    </PatternLayout>
</SMTP>

若是要使用郵件須要引入:async

<!-- Needed for SMTP appender -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

使用異步log:ide

log4j2內部使用的disruptor庫實現異步:

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

將全部logger都設置爲異步,須要在啓動參數,或者systemProperties添加:

-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

例如:

java -jar target/log4j2-demo-0.0.1-SNAPSHOT.jar -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

同步異步混合使用,須要使用<AsyncLogger> 配置元素:

<Loggers>
    <AsyncLogger name="com.example.log4j2demo" level="debug" additivity="false">
        <AppenderRef ref="ConsoleAppender" />
        <AppenderRef ref="FileAppender" />
    </AsyncLogger>

    <Root level="info">
        <AppenderRef ref="ConsoleAppender" />
        <AppenderRef ref="FileAppender" />
    </Root>
</Loggers>
相關文章
相關標籤/搜索