使用spring aop 实现请求产生唯一id。方便排查日志

一个接口被多个人同时调用,日志杂乱。
AOP
`package com.yinhai.hipay.common.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.UUID;

/**

  • description:日志生成idAop

  • @author Li Jianqiao

  • @since 2020/11/2 9:13
    /
    @Aspect
    @Configuration
    @Slf4j
    public class LogAop {
    /
    *

    • 定义切点Pointcut
    • 第一个*号:表示返回类型, *号表示所有的类型
    • 第二个号:表示类名,号表示所有的类
    • 第三个号:表示方法名,号表示所有的方法
    • 后面括弧里面表示方法的参数,两个句点表示任何参数
      /
      @Pointcut("execution(
      com.test.api.controller..(..))")
      public void executionService() {}

    /**

    • 方法调用之前调用
    • @param joinPoint
      */
      @Before(value = "executionService()")
      public void doBefore(JoinPoint joinPoint){
      String requestId = String.valueOf(UUID.randomUUID());
      MDC.put("requestId",requestId);
      log.info("=====>@Before:请求参数为:{}", Arrays.toString(joinPoint.getArgs()));
      }

    /**

    • 方法之后调用
    • @param joinPoint
    • @param returnValue 方法返回值
      */
      @AfterReturning(pointcut = "executionService()",returning="returnValue")
      public void doAfterReturning(JoinPoint joinPoint,Object returnValue){
      log.info("=====>@AfterReturning:响应参数为:{}",returnValue);
      // 处理完请求,返回内容
      MDC.clear();
      }
      }
      `
      日志xml中新增:[%X{requestId}]
      %d{yyyy-MM-dd HH:mm:ss.SSS} [%X{requestId}] [%thread] %-5level %logger{50} - %msg%n

转自:https://www.jianshu.com/p/08f5231c3d32?open_source=weibo_search

posted @ 2020-11-02 09:50  永真  阅读(587)  评论(0)    收藏  举报