spring切面打印日志

天南海北各种谈 2024-02-23 01:08:34
基本思路日志注解日志切面获取切面中参数值和返回值基本思路用AOP的around实现,注解+切面 日志注解package com.annotion;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface FuncMethodLog {}日志切面package com.aspect;import lombok.SneakyThrows;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.ArrayUtils;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.reflect.MethodSignature;import org.springframework.stereotype.Component;import java.lang.reflect.Method;import java.lang.reflect.Parameter;@Aspect@Component@Slf4jpublic FuncMethodLogAspect { @SneakyThrows @Around("@annotation(com.ccbscf.biz.zdw.annotion.FuncMethodLog)") private Object around(ProceedingJoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method targetMethod = methodSignature.getMethod(); log.info("MethodLog before, name:{}, method name:{}", targetMethod.getDeclaringClass(), targetMethod.getName()); Parameter[] parameters = targetMethod.getParameters(); Class[] parameterTypes = targetMethod.getParameterTypes(); Object[] args = joinPoint.getArgs(); if (ArrayUtils.isNotEmpty(args)) { for (int i = 0; i < args.length; i++) { log.info("MethodLog processing, parameter: {} => {}", parameterTypes[i], args[i]); } } Object rvt = joinPoint.proceed(args); log.info("MethodLog after, method return value: {}", rvt); return rvt; }}获取切面中参数值和返回值//获取参数名和参数值public void getParam(ProceedingJoinPoint proceedingJoinPoint) { Map map = new HashMap(); Object[] values = proceedingJoinPoint.getArgs(); String[] names = ((CodeSignature) proceedingJoinPoint.getSignature()).getParameterNames(); for (int i = 0; i < names.length; i++) { map.put(names[i], values[i]); }}
0 阅读:0

天南海北各种谈

简介:感谢大家的关注