首页 > 解决方案 > 获取 Spring Boot 应用程序中的日志记录级别

问题描述

我创建了一个Benchmark注释,它使用Stopwatch. Benchmark注释有一个isEnabled默认true属性。我想要的是,即使该值设置false为某种方法,如果日志记录级别为DEBUG,则进行基准测试。spring boot 中有没有办法获取应用程序的当前日志记录级别。我知道我们可以为不同的包启用多个日志记录级别。如果对于当前包或模块,日志记录级别设置为 DEBUG,则应执行基准测试。这就是我的Benchmark注释的样子:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Benchmark {

    boolean isEnabled() default true;
}

进行基准测试的方面如下所示:

@Aspect
@Component
public class BenchmarkingAspect {

    @Around("@annotation(benchmark)")
    public Object benchmarkMethodRuntimeAspect(ProceedingJoinPoint proceedingJoinPoint, Benchmark benchmark) throws Throwable {
        if (benchmark.isEnabled()) {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            Object returnedValue = proceedingJoinPoint.proceed();
            stopWatch.stop();
            log.info("Benchmarked: {} from class {}", proceedingJoinPoint.getSignature().getName(),
                    proceedingJoinPoint.getTarget().getClass().getCanonicalName());
            log.info(stopWatch.prettyPrint());
            return returnedValue;
        } else {
            return proceedingJoinPoint.proceed();
        }
    }
}

标签: javaspring-bootlogging

解决方案


我认为你可以这样做;

Logger targetLogger = LoggerFactory.getLogger(proceedingJoinPoint.getTarget().getClass())
if (targetLog.isDebugEnabled()) {
    // apply your logic here
}

推荐阅读