关于自定义注解给方法记录日志

目录

在实际生产中,总能遇到需要记录某一些方法的访问情况的,所以我们采用自定义注解来解决

自定义注解

 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Actuator {

    String type() default "1001";

}

在pom中引入

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

具体的aop类

@Aspect
@Component
public class ActuatorAop {
    private static Logger logger = LoggerFactory.getLogger(TestController.class);
    private static final ThreadLocal<TSysReqInfo> tls=new ThreadLocal<>();

    @Autowired
    private TSysReqInfoService sysReqInfoService;

    @Pointcut("@annotation(actuator)")
    public void sysApiLog( Actuator actuator) {
    }
    @Before("sysApiLog(actuator)")
    public void doBefore(JoinPoint joinPoint, Actuator actuator) {
        StringBuffer paramMsg = new StringBuffer();
        TSysReqInfo tSysReqInfo=new TSysReqInfo();
        tSysReqInfo.setReqType(actuator.type());
        try {
            logger.info("--------------aop is running----------------");
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            Parameter[] parameters = method.getParameters();
            Object[] args = joinPoint.getArgs();
            if (args != null) {
                for (int index = 0; index < args.length; index++) {
                    Object arg = args[index];
                    if (!(arg instanceof HttpServletRequest || arg instanceof HttpServletResponse)) {
                        Parameter parameter = parameters[index];
                        paramMsg.append(JSON.toJSON(arg));
                    }
                }
            }
            // 将request请求中的请求参数全部放入model中 ,并且从 自定义注解中拿出 自己定义的平台编码
            tSysReqInfo.setReqParam(paramMsg.toString());
            tSysReqInfo.setReseverTwo(method.getName());
        }catch (Exception e){
            tSysReqInfo.setReseverTwo(OutApiResCode.AOP_ERROR.getMsg());
            tSysReqInfo.setReqParam(OutApiResCode.AOP_ERROR.getCode());
            logger.error(OutApiResCode.AOP_ERROR.getMsg(),e);
        }
        tSysReqInfo.setReqTime(DateUtils.formatStr5Date(new Date()));
        tls.set(tSysReqInfo);

    }

    @AfterReturning(pointcut = "sysApiLog(actuator)", returning = "returnVal")
    public void doAfter(JoinPoint joinPoint, Object returnVal,Actuator actuator) {
        // 将respo返回参数的内容全部存入 model中,
        TSysReqInfo tSysReqInfo=tls.get();
        try {
            tSysReqInfo.setRetVal(JSON.toJSONString(returnVal));
            tSysReqInfo.setRetTime(DateUtils.formatStr5Date(new Date()));
            tSysReqInfo.setCreateTime(new Date());
            //需要 对 returnval中的参数进行处理,将返回状态做处理ret_status
            tSysReqInfo.setRetStatus(HandleApiRespUtil.judgeStatusByApiRespo(returnVal,tSysReqInfo.getRetVal()));
        }catch (Exception ex){
            tSysReqInfo.setRetStatus(OutApiResCode.AOP_ERROR.getCode());
            tSysReqInfo.setRetTime(DateUtils.formatStr5Date(new Date()));
            tSysReqInfo.setCreateTime(new Date());
            logger.error(OutApiResCode.AOP_ERROR.getMsg(),ex);
        }
        // 对结果进行异步存储 ,即使是 aop的异常也需要 记录,因为这也是一次 用户的请求
         logger.info("--------------aop is end----------------");
         sysReqInfoService.saveByAsync(tSysReqInfo);
    }


}

其中 使用了 ThreadLocal变量对同一个请求中的参数进行记录,
同时还通过注解的 type 值 对 不同的 方法类型进行分类,

猜你喜欢

转载自blog.csdn.net/sinat_27639721/article/details/79739907