简体   繁体   中英

Get the logging level in spring boot application

I have created a Benchmark annotation that gives the execution time of a method call using Stopwatch . The Benchmark annotation has an attribute isEnabled which is true by default. What I want is that even if the value if set to false for some method, if the logging level is DEBUG , the benchmarking be done. Is there a way in spring boot to get the current logging level of the application. I am aware that we can have multiple logging levels enabled for different packages. If for the current package or module, the logging level is set to DEBUG, the benchmark should be executed. This is how my Benchmark annotation looks like:

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

    boolean isEnabled() default true;
}

The aspect that does the benchmarking looks like this:

@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();
        }
    }
}

I think you can just do;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM