springboot 使用aop記錄訪問日誌

  • pom文件增加aop的依賴
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
  • 自定義註解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAnnotation {
    String value() default "";
}
  • 切面
@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.xxx.xxx.annotation.LogAnnotation)")
    public void pointcut() {
    }

    @Pointcut("execution(public * com.xxx.xxx.modules.*.controller.*.*(..))")
    public void exceptionPointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        long time = 0;
        try {
            result = point.proceed();
            time = System.currentTimeMillis() - beginTime;

            saveLog(point, time, result, null, 0);
        } catch (Throwable throwable) {
            saveLog(point, time, "", throwable, 1);

            MethodSignature methodSignature = (MethodSignature) point.getSignature();
            Class<?> returnType = methodSignature.getReturnType();
            if (returnType.getName().equalsIgnoreCase(JsonContent.class.getName())) {
                result = JsonContent.error(UtilsString.isBlank(throwable.getMessage()) ? "系統異常,請聯繫管理員!" : throwable.getMessage());
            }

            throwable.printStackTrace();
        }

        return result;
    }

    @AfterThrowing(pointcut = "exceptionPointcut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        saveLog(joinPoint, 0, "", e, 1);
    }

    private void saveLog(JoinPoint point, long time, Object result, Throwable e, int type) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = new SysLog();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        if (annotation != null) {
            sysLog.setOperation(annotation.value());
        }

        // 方法名
        String className = point.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");

        // 方法參數
        Object[] args = point.getArgs();
        LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
        String[] parameterNames = localVariableTableParameterNameDiscoverer.getParameterNames(method);
        if (args != null && parameterNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += parameterNames[i] + ": " + args[i];
                params += ", ";
            }
            sysLog.setParams(params);
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        sysLog.setIpAddress(UtilsIp.getIpAddr(request));
        sysLog.setUri(request.getRequestURI());
        sysLog.setTime(time);
        sysLog.setType(type);
        sysLog.setReturnValue(UtilsJson.obj2json(result));
        sysLog.setCreateBy("system");
        sysLog.setUpdateBy("system");

        if (e != null) {
            sysLog.setExcName(e.getClass().getName());
            sysLog.setExcMessage(e.getMessage());
        }

        sysLogService.save(sysLog);
    }

}
  • 使用
@RestController
@RequestMapping("user/manage")
public class UserManageController extends BaseController {


    @LogAnnotation("獲取用戶信息")
    @RequestMapping("info")
    public JsonContent info() throws Exception {
        throw new Exception();
    }

    /**
     * 返回成功數據,默認提示,默認handler
     *
     * @return
     */
    public JsonContent success(Object data) {
        return this.success("操作成功!", data, true);
    }
}

如果目標方法中出現異常,並由catch捕捉處理且catch又沒有拋出新的異常,那麼針對該目標方法的AfterThrowing增強處理將不會被執行。

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