springcloud 加入全局日志处理

1.编写注解和aop切面对象

在这里插入图片描述

LogDetail

@Target({
    
    ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogDetail {
    
    

    /**
     * 用来描述实体类或者方法的功能,便于找到日志发生的原始代码位置
     * @return
     */
    String value() default "";
}

LogDetailAspect

@Aspect
@Component
@Slf4j
public class LogDetailAspect {
    
    

    /**
     * 这里的within可以匹配到注解里面的方法
     */
    @Pointcut("@annotation(com.junda.annotation.LogDetail) || @within(com.junda.annotation.LogDetail)")
    public void operationLog() {
    
    
    }

    @Around("operationLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    
    
        Object result = null;
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try {
    
    
            result = joinPoint.proceed();
        } catch (Exception e) {
    
    
            stopWatch.stop();
            saveLog(false, joinPoint, DateUtil.formatBetween(stopWatch.getLastTaskTimeMillis()));
            throw e;
        }
        stopWatch.stop();
        saveLog(true, joinPoint, DateUtil.formatBetween(stopWatch.getLastTaskTimeMillis()));
        return result;
    }

    /**
     * @param flag      成功标识
     * @param joinPoint
     * @param time      花费时间
     */
    public void saveLog(Boolean flag, ProceedingJoinPoint joinPoint, String time) {
    
    
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        ApiOperation annotation = signature.getMethod().getAnnotation(ApiOperation.class);
        String value = null != annotation ? annotation.value() : "";
        Object[] args = joinPoint.getArgs();
        if (flag) {
    
    

            log.info("状态:[{}],调用的方法:[{}][{}],入参:[{}],耗时:[{}]", "请求成功", signature, value, args, time);
        } else {
    
    
            log.info("状态:[{}],调用的方法:[{}][{}],入参:[{}],耗时:[{}]", "请求失败", signature, value, args, time);
            log.error("状态:[{}],调用的方法:[{}][{}],入参:[{}],耗时:[{}]", "请求失败", signature, value, args, time);
        }

    }

}

2.扫描包

要把LogDetailAspect对象注册到容器里面,就要记得扫描
在这里插入图片描述
记得在配置文件里面把common模块引入进来,如果是maven的话记得在pom.xml里面引入进来
在这里插入图片描述

3.开始测试

请添加图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42581660/article/details/129382731