spring aop实现日志记录

用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;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring AOP是一个强大的框架,可以帮助我们实现各种切面,其中包括日志记录。下面是实现日志记录的步骤: 1. 添加Spring AOP依赖 在Maven或Gradle中添加Spring AOP依赖。 2. 创建日志切面 创建一个用于记录日志的切面。这个切面可以拦截所有需要记录日志的方法。在这个切面中,我们需要使用@Aspect注解来声明这是一个切面,并使用@Pointcut注解来定义哪些方法需要被拦截。 ```java @Aspect @Component public class LoggingAspect { @Pointcut("execution(* com.example.demo.service.*.*(..))") public void serviceMethods() {} @Around("serviceMethods()") public Object logServiceMethods(ProceedingJoinPoint joinPoint) throws Throwable { // 获取方法名,参数列表等信息 String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); // 记录日志 System.out.println("Method " + methodName + " is called with args " + Arrays.toString(args)); // 执行方法 Object result = joinPoint.proceed(); // 记录返回值 System.out.println("Method " + methodName + " returns " + result); return result; } } ``` 在上面的代码中,我们使用了@Around注解来定义一个环绕通知,它会在拦截的方法执行前后执行。在方法执行前,我们记录了该方法的名称和参数列表,然后在方法执行后记录了该方法的返回值。 3. 配置AOPSpring的配置文件中配置AOP。首先,我们需要启用AOP: ```xml <aop:aspectj-autoproxy/> ``` 然后,我们需要将创建的日志切面添加到AOP中: ```xml <bean id="loggingAspect" class="com.example.demo.aspect.LoggingAspect"/> <aop:config> <aop:aspect ref="loggingAspect"> <aop:pointcut id="serviceMethods" expression="execution(* com.example.demo.service.*.*(..))"/> <aop:around method="logServiceMethods" pointcut-ref="serviceMethods"/> </aop:aspect> </aop:config> ``` 在上面的代码中,我们将创建的日志切面声明为一个bean,并将其添加到AOP中。我们还定义了一个切入点,并将其与日志切面的方法进行关联。 4. 测试 现在,我们可以测试我们的日志记录功能了。在我们的业务逻辑中,所有匹配切入点的方法都会被拦截,并记录它们的输入和输出。我们可以在控制台中看到这些日志信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值