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);
}

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

 

posted @ 2020-12-30 18:04  御简  阅读(132)  评论(0编辑  收藏  举报