解决spring-boot使用logback的大坑

最近在写一个logback的kafka appender,无意中发现spring-boot在使用logback时的一个坑

用ConsoleAppender.java来举例,假设在logback.xml中使用了该appender,那么这个类的相关的初始化方法都会调两次,如start()方法

打断点进行debug,第一次进入start()方法如下:

可以看到所有的调用链(除了自己代码的方法)都是logback或者slf4j相关的比较正常

当跳过该断点时又会进入以此这个方法,看下调用链:

可以看到这次的初始化是由spring-boot发起的,所以这样logback初始化一次,然后spring-boot初始化一次,一共两次

我们现在可以将spring-boot的初始化去掉

debug代码可以发现LoggingApplicationListener.java这个监听器主要是用来初始化spring-boot的日志系统,现在目的将该listener在启动之前去掉

spring-boot的启动代码为:

new SpringApplicationBuilder(Launcher.class).application().run(args);

在SpringApplicationBuilder.java的构造方法打断点进行跟踪,

进入SpringAppication.java会发现该类中的代码:

private void initialize(Object[] sources) {
   if (sources != null && sources.length > 0) {
      this.sources.addAll(Arrays.asList(sources));
   }
   this.webEnvironment = deduceWebEnvironment();
   setInitializers((Collection) getSpringFactoriesInstances(
         ApplicationContextInitializer.class));
   setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
   this.mainApplicationClass = deduceMainApplicationClass();
}

第八行应该就是注册监听器的地方了,继续往下跟踪,进入以下方法:

private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type,
      Class<?>[] parameterTypes, Object... args) {
   ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
   // Use names and ensure unique to protect against duplicates
   Set<String> names = new LinkedHashSet<String>(
         SpringFactoriesLoader.loadFactoryNames(type, classLoader));
   List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
         classLoader, args, names);
   AnnotationAwareOrderComparator.sort(instances);
   return instances;
}

继续进入loadFactoryNames()方法,核心就在这里了

public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
   String factoryClassName = factoryClass.getName();
   try {
      Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
            ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
      List<String> result = new ArrayList<String>();
      while (urls.hasMoreElements()) {
         URL url = urls.nextElement();
         Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
         String factoryClassNames = properties.getProperty(factoryClassName);
         result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
      }
      return result;
   }
   catch (IOException ex) {
      throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
            "] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
   }
}

FACTORIES_RESOURCE_LOCATION这个常量的值为META-INF/spring.factories,

打开该文件可以发现:

# PropertySource Loaders
org.springframework.boot.env.PropertySourceLoader=\
org.springframework.boot.env.PropertiesPropertySourceLoader,\
org.springframework.boot.env.YamlPropertySourceLoader
# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
org.springframework.boot.context.event.EventPublishingRunListener
# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.context.web.ServerPortInfoApplicationContextInitializer
# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener,\
org.springframework.boot.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.logging.LoggingApplicationListener
# Environment Post Processors
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor
# Failure Analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.diagnostics.analyzer.BeanCurrentlyInCreationFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BeanNotOfRequiredTypeFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BindFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.NoUniqueBeanDefinitionFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.PortInUseFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ValidationExceptionFailureAnalyzer
# FailureAnalysisReporters
org.springframework.boot.diagnostics.FailureAnalysisReporter=\
org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter

ApplicationListener应该就是我们需要修改的地方了,去掉org.springframework.boot.logging.LoggingApplicationListener就可以了,我们可以在代码里面覆盖一份这块代码从而实现去掉这行,但是实际得再跑一遍,发现还是一样初始化两次

问题出在

Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
      ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));

这块代码是将所有的META-INF/spring.factories都读取过来了然后进行合并,所以说哦这个META-INF/spring.factories只能增加内容,但是不能去掉某些内容,没办法了只能在代码初始化了所有的listener之后再将listener去掉,

具体代码如下(启动spring-boot的main方法中):

SpringApplicationBuilder builder = new SpringApplicationBuilder(Launcher.class);
Set<ApplicationListener<?>> listeners = builder.application().getListeners();
for (Iterator<ApplicationListener<?>> it = listeners.iterator(); it.hasNext();) {
    ApplicationListener<?> listener = it.next();
    if (listener instanceof LoggingApplicationListener) {
        it.remove();
    }
}
builder.application().setListeners(listeners);
builder.run(args);

PS:其实log初始化两次并无伤大雅,关键是遇到了问题总是想解决下或者了解下原理

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

(0)

相关推荐

  • springboot项目配置logback日志系统的实现

    记录springboot项目配置logback日志文件管理: logback依赖jar包 SpringBoot项目配置logback理论上需要添加logback-classic依赖jar包: <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> <

  • spring boot使用logback日志级别打印控制操作

    因为公司业务需要,需要把性能日志和业务日志分开打印,用elk收集处理,所以需要对不同的业务的日志,打印到不同文件. 使用的是spring boot自带的logback. 首先在yml文件配置logback.xml文件,默认会从resources下找logback.xml文件,找不到会从yml文件中找logging.config下的指定文件. logging: level: DEBUG config: classpath:logback.xml logback.xml是logback的配置文件,可

  • 解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题

    application.properties 加入以下配置 #logback home logging.path=D:/logs/esb-producer logback.xml <property name="LOG_PATH" value="${LOG_PATH:- }" /> <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.Rolling

  • SpringBoot配置logback.xml 多环境的操作步骤

    前提 logback日志文件要实现springboot多环境配置,不然每次都需要修改logback.xml里面的配置文件,所以很麻烦. 操作步骤 1.resource文件的内容结构如下: 2.配置application.yml spring: profiles: active: dev logging: config: classpath:logback-${spring.profiles.active}.xml 3.配置lockback-dev.xml 这个地方就可以实现自己的多环境日志配置了

  • 详解Springboot之Logback的使用学习

    一.导入依赖 普通项目 <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.11</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <a

  • Springboot如何使用logback实现多环境配置?

    前言 Logback是由log4j创始人设计的又一个开源日记组件,Logback 当前分成三个模块:logback-core,logback- classic和logback-access.logback-core是其它两个模块的基础模块,logback-classic是log4j的一个改良版本.此外logback-classic完整实现SLF4J API使你可以很方便地更换成其它日记系统如log4j或JDK14 Logging.logback-access访问模块与Servlet容器集成提供通

  • springboot logback调整mybatis日志级别无效的解决

    现象 在日志配置文件 logback-spring.xml 中,无论怎么修改级别,mybatis 的 sql 日志都会打印出来. 原因 在 application.yml 中配置了 mybatis 的自定义日志类,如下: mybatis: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl 点进去查看源码,发现 debug 日志级别始终为 true,所以怎么配置都不生效 public boolean isDeb

  • springboot如何使用logback-spring配置日志格式,并分环境配置

    配置不生效的解决办法 注意:如果配置不生效,则说明spring优先加载了其他配置: 解决办法: 添加启动参数 -Dlogging.config=classpath:logback-spring.xml 修改名字为 logback.xml, SpringBoot首先去查找标准的日志配置文件,如果找不到在去找拼接Spring的配置的文件, 标准文件名: "logback-test.groovy", "logback-test.xml", "logback.gr

  • 基于spring boot 日志(logback)报错的解决方式

    记录一次报错解决方法: No converter found capable of converting from type [java.lang.String] to type [java.util.Map<java.lang.String, java.lang.String>] org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'logging.le

  • 解决Spring Boot 在localhost域奇怪的404问题(Mac book pro)

    在mac系统中,明明url是对的,浏览器也可以打开,一个简单的代码调用就是404,你有没有遇到过? 情景再现 普通的一个controller,返回一个常量. @GetMapping("/project_metadata/spring-boot") public String getMetadata(){ return "{\"data\":1234}";//这个不重要 } 调用接口的方式: content = new JSONObject(res

  • 解决spring boot 1.5.4 配置多数据源的问题

    spring boot 已经支持多数据源配置了,无需网上好多那些编写什么类的,特别麻烦,看看如下解决方案,官方的,放心! 1.首先定义数据源配置 #=====================multiple database config============================ #ds1 first.datasource.url=jdbc:mysql://localhost/test?characterEncoding=utf8&useSSL=true first.datasou

  • Spring Boot 使用 logback、logstash、ELK 记录日志文件的方法

    Spring Boot 下,尝试使用 log4j 记录日志到 logstash,在src/main/resources 目录下添加 log4j.properties 文件进行自定义输出日志文件,未能成功.在 application.yml 中 配置 logging path 打印日志成功了,但是未能调试成功日志分文件记录.网上查阅资料,说是 Spring Boot 默认使用 logback 记录日志.log4j 多次尝试后无果,遂改为使用 logback 记录,最终测试成功. 1. 关于 Spr

  • 解决Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)的序列化问题

    LocalDate . LocalTime . LocalDateTime 是Java 8开始提供的时间日期API,主要用来优化Java 8以前对于时间日期的处理操作.然而,我们在使用Spring Boot或使用Spring Cloud Feign的时候,往往会发现使用请求参数或返回结果中有 LocalDate . LocalTime . LocalDateTime 的时候会发生各种问题.本文我们就来说说这种情况下出现的问题,以及如何解决. 问题现象 先来看看症状.比如下面的例子: @Sprin

  • 解决Spring Boot 正常启动后访问Controller提示404问题

    问题描述 今天重新在搭建Spring Boot项目的时候遇到访问Controller报404错误,之前在搭建的时候没怎么注意这块.新创建项目成功后,作为项目启动类的Application在com.blog.start包下面,然后我写了一个Controller,然后包的路径是com.blog.ty.controller用的@RestController 注解去配置的controller,然后路径也搭好了,但是浏览器一直报404.最后找到原因是Spring Boot只会扫描启动类当前包和以下的包 ,

  • 解决Spring Boot项目端口8080被占用的问题

    错误提示: 2018-11-12 21:25:58.422 ERROR 15916 - [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter : APPLICATION FAILED TO START Description: The Tomcat connector configured to listen on port 8080 failed to start. The port may already be in use or t

  • 解决Spring Boot 多模块注入访问不到jar包中的Bean问题

    情景描述 一个聚合项目spring-security-tutorial,其中包括4个module,pom如下所示: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://mav

  • 解决spring boot启动扫描不到自定义注解的问题

    对于自定义注解这里就不唠叨了,百度一大堆,这里有我一个自定义注解 @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD }) public @interface MsgEvent { RetailOrderEvent msgEvent(); } 注解实现类 @Component public class MsgEventProcessor implements BeanPostProcessor { /** * 事件消息

  • 解决Spring boot 嵌入的tomcat不启动问题

    此文章记录一次spring boot通过main 方法启动无法成功的问题 Unregistering JMX-exposed beans on shutdown 问题如下,因为已经解决用的别人的截图但是效果是一样的 百度了一圈都说tomcat没有配置,但实际xml有如下配置 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomc

随机推荐