springcloud adds global log processing

1. Write annotations and aop aspect objects

Insert image description here

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. Scan the package

To register the LogDetailAspect object into the container, remember to scan.
Insert image description here
Remember to introduce the common module in the configuration file. If it is maven, remember to introduce it in pom.xml.
Insert image description here

3. Start testing

Please add image description

Guess you like

Origin blog.csdn.net/weixin_42581660/article/details/129382731