springboot替换logback为高性能日志框架log4j2(异步方式)完整代码!

点个关注,不要白嫖奥~~~

1.首先把项目中有关logback的全删掉
2.替换对应的pom文件依赖

  <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-web</artifactId>
  </dependency>

  <!-- 引入log4j2依赖 -->
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-log4j2</artifactId>
  </dependency>

  <!--开启日志异步,异步logger打印日志性能最好 -->
  <dependency>
      <groupId>com.lmax</groupId>
      <artifactId>disruptor</artifactId>
      <version>${disruptor.version}</version>
  </dependency>

3.在resources文件夹下创建文件log4j2-spring.xml,添加如下内容

<?xml version="1.0" encoding="UTF-8"?>
<configuration monitorInterval="5">


    <!--变量配置-->
    <Properties>
        <property name="LOG_PATTERN" value="%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"/>
        <property name="FILE_PATH" value="${ctx:logPath}"/>
        <property name="FILE_NAME" value="cloud-monitor"/>
    </Properties>

    <appenders>

        <console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="${LOG_PATTERN}"/>
            <ThresholdFilter level="${ctx:logLevel}" onMatch="ACCEPT" onMismatch="DENY"/>
        </console>

        <File name="FileLog" fileName="${FILE_PATH}/test.log" append="false">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </File>

        <RollingFile name="RollingFileInfo" fileName="${FILE_PATH}/info.log"
                     filePattern="${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz">

            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="${LOG_PATTERN}"/>
            <Policies>
                <!--interval属性用来指定多久滚动一次,默认是1 hour-->
                <TimeBasedTriggeringPolicy interval="1"/>
                <SizeBasedTriggeringPolicy size="10MB"/>
            </Policies>
            <DefaultRolloverStrategy max="15"/>
        </RollingFile>

        <RollingFile name="RollingFileWarn" fileName="${FILE_PATH}/warn.log"
                     filePattern="${FILE_PATH}/${FILE_NAME}-WARN-%d{yyyy-MM-dd}_%i.log.gz">

            <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="${LOG_PATTERN}"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1"/>
                <SizeBasedTriggeringPolicy size="10MB"/>
            </Policies>
            <DefaultRolloverStrategy max="15"/>
        </RollingFile>

        <RollingFile name="RollingFileError" fileName="${FILE_PATH}/error.log"
                     filePattern="${FILE_PATH}/${FILE_NAME}-ERROR-%d{yyyy-MM-dd}_%i.log.gz">
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="${LOG_PATTERN}"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1"/>
                <SizeBasedTriggeringPolicy size="10MB"/>
            </Policies>
            <DefaultRolloverStrategy max="15"/>
        </RollingFile>

    </appenders>


    <loggers>
        <Logger name="org.springframework" level="info" additivity="false">
            <AppenderRef ref="Console"/>
        </Logger>
        <root level="info" includeLocation="true">
            <appender-ref ref="Console"/>
            <appender-ref ref="FileLog"/>
            <appender-ref ref="RollingFileInfo"/>
            <appender-ref ref="RollingFileWarn"/>
            <appender-ref ref="RollingFileError"/>
        </root>
    </loggers>

</configuration>

4.在resources文件夹下创建文件log4j2.component.properties,添加如下内容

# 设置异步日志系统属性
log4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

5.yml文件中我是这么配置的
在这里插入图片描述
6.在config文件夹下新建class,名字就叫ApplicationStartedEventListener

package com.mec.core.config;


import com.mec.core.constant.Constants;
import com.mec.core.utils.RequestUtil;
import org.slf4j.MDC;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Map;

public class ApplicationStartedEventListener implements GenericApplicationListener {

    public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 10;

    private static Class<?>[] EVENT_TYPES = {ApplicationStartingEvent.class, ApplicationEnvironmentPreparedEvent.class,
            ApplicationPreparedEvent.class, ContextClosedEvent.class, ApplicationFailedEvent.class};

    private static Class<?>[] SOURCE_TYPES = {SpringApplication.class, ApplicationContext.class};

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            ConfigurableEnvironment env = ((ApplicationEnvironmentPreparedEvent) event).getEnvironment();
            MutablePropertySources mps = env.getPropertySources();
            Map<String, String> contextMap = new HashMap<>();
            PropertySource<?> ps = mps.get("applicationConfig: [classpath:/application.yaml]");
            if(ps != null){
                //判断yml文件中是否存在日志路径
                if (ps.containsProperty("logging.logPath")) {
                    String logs = (String) ps.getProperty("logging.logPath");
                    String path = RequestUtil.getContentInfo(logs);
                    path = path.substring(path.indexOf(':') + 1);
                    contextMap.put(Constants.RequestActionVariables.LOG_PATH, path);
                }
                //判断yml文件中是否存在日志级别
                if (ps.containsProperty("logging.level.org.apache.http")) {
                    String logs = (String) ps.getProperty("logging.level.org.apache.http");
                    String level = RequestUtil.getContentInfo(logs);
                    level = level.substring(level.indexOf(':') + 1);
                    contextMap.put(Constants.RequestActionVariables.LOG_LEVEL, level);
                }
            }else {
                contextMap.put(Constants.RequestActionVariables.LOG_PATH, Constants.RequestActionVariables.DEFAULT_LOG_PATH);
                contextMap.put(Constants.RequestActionVariables.LOG_LEVEL, Constants.RequestActionVariables.DEFAULT_LOG_LEVEL);
            }
            MDC.setContextMap(contextMap);

        }

    }

    @Override
    public int getOrder() {
        return DEFAULT_ORDER;
    }

    @Override
    public boolean supportsEventType(ResolvableType resolvableType) {
        return isAssignableFrom(resolvableType.getRawClass(), EVENT_TYPES);
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return isAssignableFrom(sourceType, SOURCE_TYPES);
    }

    private boolean isAssignableFrom(Class<?> type, Class<?>... supportedTypes) {
        if (type != null) {
            for (Class<?> supportedType : supportedTypes) {
                if (supportedType.isAssignableFrom(type)) {
                    return true;
                }
            }
        }
        return false;
    }
}

使用到的Constants文件

package com.mec.core.constant;



public final class Constants {

    private Constants(){}

    public static class RequestActionVariables {

        private RequestActionVariables(){}

        public static final String LOG_PATH = "logPath";

        public static final String DEFAULT_LOG_PATH = "/usr/app/log";

        public static final String LOG_LEVEL = "logLevel";

        public static final String DEFAULT_LOG_LEVEL = "info";

    }
}

7.OK完成了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RayCheungQT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值