Spring中使用AOP实现日志打印

766 阅读1分钟

看到项目中有很多使用AOP实现的自定义注解,很好用,学习一下~

@DeviceInfoAop 设备信息
@LoginCheck    校验用户登录
@UserInfo      用户信息
@LogAspect     aop打日志
@WatchdogHelperAop  打点(埋点)

AOP中解析的数据可以放到Threadlocal中,搭配使用效果更佳 -> ThreadLocal - 一直搞不懂的知识

1. 日志打印AOP

@Slf4j
@Aspect
@Component
public class ControllerAop {

    // 切入点表达式:用来指定哪些类需要代理
    @Pointcut("execution(* com.balloon..controller.*(..))")
    public void controllerPointcut() {
    }

    @Around("controllerPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        boolean hasException = false;
        String method = joinPoint.getSignature().toShortString();
        Result<?> result = null;
        try {
            Object obj = joinPoint.proceed();
            if (obj instanceof Result) {
                result = (Result<?>) obj;
            }
            return obj;
        } catch (Throwable e) {
            log.error("[Controller] {}执行异常, param={}", method, JSONUtil.toJSONString(joinPoint.getArgs()), e);
            hasException = true;
            throw e;
        } finally {
            String cost = String.valueOf(System.currentTimeMillis() - start);
            String suc = "-", code = "-", msg = "-";
            if (result != null) {
                suc = String.valueOf(Result.isSuccess(result));
                code = String.valueOf(result.getCode());
                msg = result.getMsg();
            }
            log.info("[Controller] {}执行结束, 耗时{}ms, exception={}, suc={}, code={}, msg={}", method, cost, hasException, suc,
                    code, msg);
        }
    }

}

从0到1的学习