zoukankan      html  css  js  c++  java
  • 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);
    }

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

  • 相关阅读:
    wrap添加及去除外层dom的方法
    闭包作用域探究小例
    测试模型之W模型(脑图)
    软件测试模型之前置模型(脑图)
    软件测试模型之H模型(脑图)
    软件测试基础(脑图)
    测试模型之V模型(脑图)
    一个点型的rsyncd.conf内容
    rsync同步时报name lookup failed for name or service not known错误的解决方法
    ubuntu下的eclipse 3.3初用aptana报SWT错误
  • 原文地址:https://www.cnblogs.com/SamNicole1809/p/14212768.html
Copyright © 2011-2022 走看看