1. 程式人生 > >springBoot AOP環繞增強、自定義註解、log4j2、MDC

springBoot AOP環繞增強、自定義註解、log4j2、MDC

(一)log4j2 maven配置

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <!-- 切換log4j2日誌讀取 -->
                <exclusion>
                    <
groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency>
 <!-- 配置 log4j2 -->
        <dependency>
            <
groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> <!-- 加上這個才能辨認到log4j2.yml檔案 --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <
artifactId>jackson-dataformat-yaml</artifactId> </dependency>

在resources 資料夾下建立log4j2.yml 檔案

Configuration:
  status: warn
  Properties: # 定義全域性變數
    Property: # 預設配置(用於開發環境)。其他環境需要在VM引數中指定,如下:
      #測試:-Dlog.level.console=warn -Dlog.level.xjj=trace
      #生產:-Dlog.level.console=warn -Dlog.level.xjj=info
      - name: log.level.console
        value: trace
      - name: log.level.xjj
        value: trace
      - name: log.path
        value: D:/Logs/log
      - name: project.name
        value: my-spring-boot
  Appenders:
    Console:  #輸出到控制檯
      name: CONSOLE
      target: SYSTEM_OUT
      ThresholdFilter:
        level: ${sys:log.level.console} # “sys:”表示:如果VM引數中沒指定這個變數值,則使用本檔案中定義的預設全域性變數值
        onMatch: ACCEPT
        onMismatch: DENY
      PatternLayout:
        pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m %X{REQUESTID} %n"
    RollingFile: # 輸出到檔案,超過128MB歸檔
      - name: ROLLING_FILE
        ignoreExceptions: false
        fileName: ${log.path}/${project.name}.log
        filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
        PatternLayout:
          pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m %X{REQUESTID} %n"
        Policies:
          SizeBasedTriggeringPolicy:
            size: "128 MB"
        DefaultRolloverStrategy:
          max: 1000
  Loggers:
    Root:
      level: info
      AppenderRef:
        - ref: CONSOLE
        - ref: ROLLING_FILE
    Logger: # 為com.xjj包配置特殊的Log級別,方便除錯
      - name: com.xjj
        additivity: false
        level: ${sys:log.level.xjj}
        AppenderRef:
          - ref: CONSOLE
          - ref: ROLLING_FILE

其中 %X{REQUESTID} 為MDC設定的請求標識,每個請求都會有,用於跟蹤日誌。

(二)MDC和AOP 環繞增強、自定義註解

建立日誌類

public class tools_log {
    public static Logger getLogger(Class class_) {
        Logger logger = LoggerFactory.getLogger(class_);
        return logger;
    }
}//end

AOP、MDC

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Pointcut("execution(public * 包路徑..*.*(..))")
    public void LogHelp() {
    }

    @Pointcut("@annotation(自定義註解路徑)")
    public void noAnnotation() {
    }

    final Logger logger = tools_log.getLogger(this.getClass());

    @Around("LogHelp()&&!noAnnotation()")
    public Object arround(ProceedingJoinPoint joinPoint) {
        MDC.put("REQUESTID", UUID.randomUUID().toString());
        logger.info("方法環繞start.....");
        // 接收到請求,記錄請求內容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 記錄下請求內容
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS : " + JSON.toJSONString(joinPoint.getArgs()));
        try {
            Object o = joinPoint.proceed();
            logger.info("方法環繞proceed,結果是 :" + o);
            return o;
        } catch (Throwable e) {
            logger.error(e.toString());
            return null;
        } finally {
            MDC.clear();
        }
    }
}//end

.. 表示匹配多個引數

*  表示匹配一個引數

.* 表示匹配多個類

 

自定義註解

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface noAroundAnno {
}//end

定義在方法上