spring aop打印日誌

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {

  /**
   * 操作
   */
  String operate() default "";

  /**
   * 模塊
   */
  String module() default "";

}
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Component
@Aspect
@Slf4j
public class LogAspect {

  /**
   * 切點 注意:這裏的路徑最好寫全路徑 不寫全有時會有錯誤
   * <p>
   * 參數說明: 使用@annotation時,所修飾的方法或是接口都會被攔截。 使用execution時,指定你要切入的一個地方。
   */
  @Pointcut("@annotation(cn.wanda.sail.member.aop.LogAnnotation)")
  public void pointcut() {
  }

  /**
   * 通知 注意:對應上面得切點方法名稱
   */
  @Around("pointcut()")
  public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);

    Map<String, Object> paramMap = getNameAndValue(joinPoint);

    // 記錄開始時長
      long beginTime = System.currentTimeMillis();
      log.info("模塊:{}, 操作:{}, 方法:{}.{}, \n參數:{}", logAnnotation.module(),
          logAnnotation.operate(),
          joinPoint.getTarget().getClass().getName(), signature.getName(),
          JackJsonUtils.toJSONString(paramMap));

    // 執行方法
    Object result = joinPoint.proceed();
    // 執行時長(毫秒)
    long time = System.currentTimeMillis() - beginTime;
    // 記錄日誌
    log.info("返回:{}. 耗時:{}", JackJsonUtils.toJSONString(result), time);
    return result;
  }


  /**
   * 獲取參數Map集合
   */
  Map<String, Object> getNameAndValue(ProceedingJoinPoint joinPoint) {
    Map<String, Object> param = new HashMap<>();
    Object[] paramValues = joinPoint.getArgs();
    String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();
    for (int i = 0; i < paramNames.length; i++) {
      param.put(paramNames[i], paramValues[i]);
    }
    return param;

  }
}
@RestController
@RequestMapping("/test")
public class TestController {

  @PostMapping("post")
  @LogAnnotation
  public String post(@RequestBody Object member){
    System.out.println(member);
    return "Java Aop";
  }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章