• springboot 日志处理 aop


    使用AOP进行操作日志和异常日志处理。

    操作日志:

    1、定义annotation,可参考自己的需要进行修改

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Log {
        // 模块
        String model();
        // 类型
        int type();
        // 说明
        String desc();
    }

    2、AOP捕获注释的方法

    @Pointcut("@annotation(com.注解所在包.Log)")
    private void log() {}
    
    @AfterReturning("log() && @annotation(log)")
    public void logHandler(Log log) {
        asyncService.saveLogOperation(log);  // 异步写入日志,log.model(),log.type(),log.desc()获取属性
    }

    3、在controller方法上添加注解(示例)

    @Log(model = "m", type = LogType.MODIFY, desc = "修改内容")
    public String method() { ... }

    异常日志:

    1、AOP捕获异常

    @Pointcut("execution(* com.自己的包.controller..*(..))")
    private void execption() {}
    
    @AfterThrowing(pointcut = "execption()", throwing = "e")
    public void execptionHandler(JoinPoint joinPoint, Throwable e) {
        asyncService.saveLogException(joinPoint, e);  // 异步写异常日志,JoinPoint可以反射获取方法
    }

    利用JoinPoint获取请求的类名和方法名

    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Method method = methodSignature.getMethod();
    String methodName = method.getName();
    String className = joinPoint.getTarget().getClass().getName();

    获取HttpServletRequest

    private HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
    }

    通过上述两者和异常,即可获得大部分需要的参数,具体方式可自行查询,资源丰富。

  • 相关阅读:
    deleted
    deleted
    deleted
    deleted
    deleted
    deleted
    POJ 1840 Eqs(乱搞)题解
    UVALive 6955 Finding Lines(随机化优化)题解
    CodeForces 828E DNA Evolution(树状数组)题解
    UVA 11019 Matrix Matcher(二维hash + 尺取)题解
  • 原文地址:https://www.cnblogs.com/SamNicole1809/p/14212768.html
Copyright © 2020-2023  润新知