欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring aop实现日志记录

程序员文章站 2022-07-15 11:11:14
...

用Spring aop实现日志操作记录(基于自定义注解实现)

首先自定义一个注解,此注解用在controller中的方法上,用于拦截参数

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OprationLog {
}

然后写一个拦截器用于保存日志

@Component
@Slf4j
@Aspect
public class AopLogIntecepAspect {

    @Autowired
    OprationRemoteService oprationRemoteService; //用于保存日志的bean
    
    private static String LOGTEMPLATE = "{\"elapse\":\"%s\",\"interface\":\"%s\",\"method\":\"%s\",\"params\":%s,\"result\":%s}";

    // 配置织入点,自定义注解的路径
    @Pointcut("@annotation(com.weimob.saas.knowledge.aop.OprationLog)")
    public void logPointCut() {
    }

    /**
     * 前置通知 用于拦截操作,在方法返回后执行
     */
    @Around(value = "logPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

		//接入cat监控,可删除
        Transaction cat = Cat.newTransaction(getInterface(joinPoint), getRequestMethod(joinPoint));
        Object obj;
        Long elapsedMills = System.currentTimeMillis();

        try {
            obj = joinPoint.proceed();
            cat.setStatus(Transaction.SUCCESS);
        } catch (Throwable throwable) {
            cat.setStatus(throwable);
            throwable.printStackTrace();
            throw throwable;
        } finally {
            cat.complete();
        }

        elapsedMills = System.currentTimeMillis() - elapsedMills;
        aopLogs(elapsedMills, joinPoint, obj); //保存日志方法
        return obj;
    }

    private String getRequestMethod(ProceedingJoinPoint joinPoint) {
        try {
            Signature signature = joinPoint.getSignature();

            if (!(signature instanceof MethodSignature)) {
                throw new IllegalArgumentException("obtain method  failure!");
            }
            MethodSignature methodSignature = (MethodSignature) signature;
            return methodSignature.getName();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    private String getInterface(ProceedingJoinPoint joinPoint) {
        return joinPoint.getTarget().getClass().getName();
    }

    private void aopLogs(Long time,ProceedingJoinPoint joinPoint,Object object) {
        String targetName = getInterface(joinPoint);
        String methodName = getRequestMethod(joinPoint);
        // 获得注解
        OprationLog controllerLog = getAnnotationLog(joinPoint);
        if (controllerLog == null) {
            return;
        }

        List params = new ArrayList();
        Object[] obj = joinPoint.getArgs();
        for (Object o : obj) {
            if (o instanceof HttpServletRequest) {
                Map<String, String[]> map = ((HttpServletRequest) o).getParameterMap();
                for (Map.Entry<String, String[]> entry : map.entrySet()) {
                    params.add(entry.getKey() + "=" + Arrays.toString(entry.getValue()));
                }
            } else if (o instanceof HttpServletResponse) {
                continue;
            } else {
                params.add(FastJsonUtils.beanToJson(o));
            }
        }

        String message = String.format(LOGTEMPLATE, time, targetName, methodName, params, FastJsonUtils.beanToJson(object));
        log.info(message);

		//保存日志到数据库
        OperationLogDto operationLog = new OperationLogDto();
        operationLog.setAccount(ThreadUtil.threadLocal.get());
        operationLog.setMethod(methodName);
        operationLog.setContent(message);
        oprationRemoteService.saveOperationLog(operationLog);
    }

    /**
     * 是否存在注解,如果存在就获取
     */
    private static OprationLog getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(OprationLog.class);
        }
        return null;
    }
}
相关标签: java