java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > logback日志级别设置无效

logback日志级别设置无效问题及解决

作者:shuxiaohua

文章总结:文章介绍了在Spring Boot项目中配置日志级别时,优先级问题,通过查阅资料发现,配置文件中的logging.level.xx也能配置日志级别,且优先级比logback.xml高,文章还提供了源码分析,说明了Spring Boot如何处理日志级别配置

背景

项目同事在定位定时任务没执行时发现,定时任务中的日志没有打印,改成WARN后能够正常打印(代码中log.info()改为log.warn())。

检查logback.xml中发现对应的日志级别为INFO级别,当时不清楚还有哪里能够配置日志级别,遂百度查阅资料。

原来配置文件中的logging.level.xx也能配置日志级别,且优先级比logback.xml高。以下是源码分析。

源码分析

首先spring的配置项

都会在spring-configuration-metadata.json中进行说明,因此在IDE中搜索该关键字,查看配置项的说明。

    {
      "name": "logging.level",
      "type": "java.util.Map<java.lang.String,java.lang.String>",
      "description": "Log levels severity mapping. For instance, `logging.level.org.springframework=DEBUG`.",
      "sourceType": "org.springframework.boot.context.logging.LoggingApplicationListener"
    }

从内容中可以看到

该配置项由org.springframework.boot.context.logging.LoggingApplicationListener处理。

	protected void setLogLevels(LoggingSystem system, ConfigurableEnvironment environment) {
		BiConsumer<String, LogLevel> customizer = getLogLevelConfigurer(system);
		Binder binder = Binder.get(environment);
		# 从配置中获取日志级别的配置项
		Map<String, LogLevel> levels = binder.bind(LOGGING_LEVEL, STRING_LOGLEVEL_MAP).orElseGet(Collections::emptyMap);
		levels.forEach((name, level) -> configureLogLevel(name, level, customizer));
	}

	private void configureLogLevel(String name, LogLevel level, BiConsumer<String, LogLevel> configurer) {
		if (this.loggerGroups != null) {
			LoggerGroup group = this.loggerGroups.get(name);
			if (group != null && group.hasMembers()) {
				group.configureLogLevel(level, configurer);
				return;
			}
		}
		# 代码会走到这里
		configurer.accept(name, level);
	}

配置logging.level.org=ERROR调试代码如下

可以看到通过logfactory获取logger后

使用logging.level配置项重新覆盖了其日志级别,所以配置项中的日志级别高于logback.xml中的日志级别。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文