spring Boot使用AOP統一處理Web請求日誌記錄

1.使用spring boot實現一個攔截器web

  一、引入依賴spring

  

< dependency >
   < groupId >org.springframework.boot</ groupId >
   < artifactId >spring-boot-starter-aop</ artifactId >
</ dependency >
 
 二、建立攔截器類(在該類中,定義了攔截規則:攔截com.xjj.web.controller包下面的全部類中,有@RequestMapping註解的方法。):
 

/**
* 攔截器:記錄O2O調用接口記錄
*/
@Aspect
@Component
public class O2oInterfaceInterceptor {數據庫

  @Autowired
  private SysCallInterfaceLogRepository sysCallInterfaceLogRepository;
  @Autowired
  private SysEmailService sysEmailService;
  @Autowired
  private SysPropertyService sysPropertyService;

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

/**
* 定義攔截規則:攔截com.ctop.wms.interfaces.ActivitiInterfaces包下面的全部類中,有@RequestMapping註解的方法。併發


*/
  @Pointcut("execution(* com.ctop.wms.interfaces.ActivitiInterfaces.*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)")
  public void controllerMethodPointcut() {}

  @Around("controllerMethodPointcut()")
  public Object controllerMethodPointcutInterceptor(ProceedingJoinPoint pjp) {
    return Interceptor(pjp);
  }
/**
* 攔截器具體實現
* @param pjp
* @return JsonResult(被攔截方法的執行結果)
*/
  public Object Interceptor(ProceedingJoinPoint pjp){
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Method method = signature.getMethod(); //獲取被攔截的方法
    String methodName = method.getName(); //獲取被攔截的方法名
    String ip = request.getRemoteAddr();
    String url = request.getRequestURL().toString();
    logger.info("被調接口,請求開始----------------------------");
    logger.info("ip : " + request.getRemoteAddr());
    logger.info("url : " + request.getRequestURL().toString());
    logger.info("methodName : " + methodName);

    Object result = "";
    String param = Arrays.toString(pjp.getArgs());

    logger.info("param : " + param);
    SysCallInterfaceLog log = new SysCallInterfaceLog();
    log.setExt1("called");// 被叫
    log.setRequestIp(ip);
    log.setRequestMethod(methodName);
    log.setRequestParam(param);
    log.setRequestUrl(url);app

    try {
      // 一切正常的狀況下,繼續執行被攔截的方法
      result = pjp.proceed();
      String resultStr = "";
      if(result != null) {
        if(result instanceof String) {
          resultStr = (String) result;
        } else {
          Gson gson = new Gson();
          resultStr = gson.toJson(result);
        }
      }

      log.setResult(resultStr);
      logger.info("result : " + resultStr);
      logger.info("請求結束,請求成功");

      // 記錄結果到數據庫
      log.setSuccess("success");
      log = sysCallInterfaceLogRepository.save(log);
    } catch (Throwable e) {
      logger.info("請求結束,請求失敗");
      // 記錄結果到數據庫, 併發送郵件
      log.setSuccess("fail");
      Gson gson = new Gson();
      String exceptionStr = gson.toJson(e);
      log.setResult(exceptionStr);

      SysProperty sysPropertyName= sysPropertyService.getSysProperty("o2o.wms.log.name");
      SysProperty sysPropertyEmail= sysPropertyService.getSysProperty("o2o.wms.log.email");
      log = sysCallInterfaceLogRepository.save(log);
      SysEmailDto sysEmailDto = new SysEmailDto();
      List<SysEmailInfoDto> sysEmailInfoDtoLs = new ArrayList<SysEmailInfoDto>();
      SysEmailInfoDto dtoDetails = new SysEmailInfoDto();
      if(sysPropertyName !=null && sysPropertyEmail !=null){
          dtoDetails.setReceiverEmail(sysPropertyEmail.getPropValue());
          dtoDetails.setReceiverName(sysPropertyName.getPropValue());
      }
      sysEmailDto.setTitle("O2O調用WMS接口失敗日誌!");
      sysEmailDto.setContent("調用:"+url+"失敗!sys_Call_Interface_Log.Scil_Uuid="+log.getScilUuid()+",\n請求參數:"+param+",\n調用結果:"+exceptionStr);
      sysEmailInfoDtoLs.add(dtoDetails);
      sysEmailDto.setSysEmailInfoDto(sysEmailInfoDtoLs);
      try {
        sysEmailService.addSysEmail(sysEmailDto);
      } catch (Exception e1) {
        e1.printStackTrace();
      }
    e.printStackTrace();
    throw new BusinessException(e, null, null);
   }
  return result;
  }


}spring-boot

相關文章
相關標籤/搜索