Aop实现记录请求日志



/**
 * @ClassName: LogAspect
 * @Description: 日志记录AOP实现
 */
@Component
@Aspect
public class LogAspect {

  private final static Logger logger = LoggerFactory.getLogger(LogAspect.class);

  @Pointcut("execution(* com.**.**.**.controller.*.*(..))")
  public void pointcut() {
  }

  /**
   * 记录程序运行时候抛出的异常信息
   */
  @AfterThrowing(pointcut = "pointcut()", throwing = "ex")
  public void doThrowing(JoinPoint joinPoint, Exception ex) {
    HttpServletRequest request;
    try {
      request = getHttpServletRequest();
    } catch (Exception e) {
      return;
    }
    // 获取输入参数
    String queryString = request.getQueryString();
    String method = request.getMethod();
    String params = "";
    if ("get".equalsIgnoreCase(method)) {
      params = queryString;
    } else if ("post".equalsIgnoreCase(method)) {
      params = JsonUtils.getJSONString(request.getParameterMap());
    }
    String methodName = joinPoint.getSignature().getName();
    logger.error("[请求:[{}];参数:[{}];方法:[{}]发生异常,原因: ]",
        request.getRequestURI(), params, methodName, ex);
  }

  private HttpServletRequest getHttpServletRequest() {
    RequestAttributes ra = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes sra = (ServletRequestAttributes) ra;
    return sra.getRequest();
  }

  /**
   * @Title:doAround
   * @Description: 环绕触发
   */
  @Around(value = "pointcut()")
  public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    long startTime = System.currentTimeMillis();
    HttpServletRequest request;
    HttpSession session;
    try {
      request = getHttpServletRequest();
      session = request.getSession();
    } catch (Exception e) {
      return pjp.proceed();
    }
    // 获取输入参数
    String queryString = request.getQueryString();
    String method = request.getMethod();
    String requestURI = request.getRequestURI();
    String params = "";
    if ("get".equalsIgnoreCase(method)) {
      params = queryString;
    } else if ("post".equalsIgnoreCase(method)) {
      params = JsonUtils.getJSONString(request.getParameterMap());
    }
    // 执行完方法的返回值:调用proceed()方法,就会触发切入点方法执行
    Object result = pjp.proceed();// result的值就是被拦截方法的返回值

    logger.info("[用户[{}];请求:[{}];请求方式:[{}];参数:[{}];结果:[{}]; 耗时:[{}]ms]",
        session.getAttribute(USER), requestURI, method, params,
        result, System.currentTimeMillis() - startTime);
    return result;
  }

}

你可能感兴趣的:(Aop实现记录请求日志)