springcloud はグローバルログ処理を追加します

1. アノテーションと AOP アスペクト オブジェクトを記述する

ここに画像の説明を挿入します

ログ詳細

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

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

ログ詳細アスペクト

@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 オブジェクトをコンテナに登録するには、必ずスキャンしてください、
ここに画像の説明を挿入します
設定ファイルに共通モジュールを必ず導入してください、Maven の場合は、pom.xml に忘れずに導入してください。
ここに画像の説明を挿入します

3. テストを開始する

画像の説明を追加してください

おすすめ

転載: blog.csdn.net/weixin_42581660/article/details/129382731