SpringBoot揭密:spring-boot-starter-logging及源码解析

868 阅读2分钟

​​本文已参与「新人创作礼」活动,一起开启掘金创作之路。

        SpringBoot源码中使用的日志API为JCL(Java common log),JCL实际上只是一个日志门面,没有具体的日志功能实现。如果将SpringBoot中的spring-boot-start-logging依赖排除,可以看到启动项目时打印的是红色字体的JUL日志。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

         如果不刻意的排除spring-boot-starter-logging,SpringBoot默认引入的logback日志,SpringBoot在一站式启动过程中,会发布各种通知事件,如项目正在启动事件,准备环境事件等,logback的加载就是通过事件监听者来响应上述事件从而触发的,关于SpringBoot的事件编程模型原理可参考文章:SpringBoot揭密:SpringBoot里的观察者设计模式,SpringBoot事件编程模型解析,这里不再赘述。

        触发加载的原理与SpringBoot配置文件触发加载的过程是同理的,SpringBoot引入了一些新的监听器,从spring.factories文件中就能看到具体的监听器:

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
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.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

         其中ConfigFileApplicationListener就是加载SpringBoot配置文件的监听器,LoggingApplicationListener就是加载日志的监听器。可以看到类中onApplicationEvent方法就是处理监听到的各种事件的:

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof ApplicationStartingEvent) {
			onApplicationStartingEvent((ApplicationStartingEvent) event);
		}
		else if (event instanceof ApplicationEnvironmentPreparedEvent) {
			onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event);
		}
		else if (event instanceof ApplicationPreparedEvent) {
			onApplicationPreparedEvent((ApplicationPreparedEvent) event);
		}
		else if (event instanceof ContextClosedEvent
				&& ((ContextClosedEvent) event).getApplicationContext().getParent() == null) {
			onContextClosedEvent();
		}
		else if (event instanceof ApplicationFailedEvent) {
			onApplicationFailedEvent();
		}
	}

        先是第一个事件:ApplicationStartingEvent

private void onApplicationStartingEvent(ApplicationStartingEvent event) {
  this.loggingSystem = LoggingSystem.get(event.getSpringApplication().getClassLoader());
  this.loggingSystem.beforeInitialize();
}

        LoggingSystem.get方法就是记载具体日志的过程:

public static LoggingSystem get(ClassLoader classLoader) {
  String loggingSystem = System.getProperty(SYSTEM_PROPERTY);
  if (StringUtils.hasLength(loggingSystem)) {
    if (NONE.equals(loggingSystem)) {
      return new NoOpLoggingSystem();
    }
    return get(classLoader, loggingSystem);
  }
  return SYSTEMS.entrySet().stream().filter((entry) -> ClassUtils.isPresent(entry.getKey(), classLoader))
      .map((entry) -> get(classLoader, entry.getValue())).findFirst()
      .orElseThrow(() -> new IllegalStateException("No suitable logging system located"));
}

        这里其实是遍历SYSTEMS里面的entry,判断key代表的class是否存在,如果存在就把value代表的那个LoggingSystem给加载了,看下SYSTEMS里面都有啥:

private static final Map<String, String> SYSTEMS;
static {
  Map<String, String> systems = new LinkedHashMap<>();
  systems.put("ch.qos.logback.core.Appender", "org.springframework.boot.logging.logback.LogbackLoggingSystem");
  systems.put("org.apache.logging.log4j.core.impl.Log4jContextFactory","org.springframework.boot.logging.log4j2.Log4J2LoggingSystem");
  systems.put("java.util.logging.LogManager", "org.springframework.boot.logging.java.JavaLoggingSystem");
  SYSTEMS = Collections.unmodifiableMap(systems);
}

        这里默认添加了3个日志框架,依次是logback、log4j2和jdk的log,因为spring-boot-starter-logging默认依赖了logback,因此,logback会被初始化使用,再这里产生了实例LogbackLoggingSystem。

        第二个事件:ApplicationEnvironmentPreparedEvent,开始通过LogBackLoggingSystem配置LogBack,如果配置了自定义的日志配置文件就加载自己的文件,否则加载默认的配置文件。

        Logback整合完成后,SpringBoot中的JCL API打印的日志是如何转变成logback格式的呢,这里看下spring-boot-starter-logging pom中引入的依赖:

<dependencies>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-to-slf4j</artifactId>
      <version>2.13.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jul-to-slf4j</artifactId>
      <version>1.7.30</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

        这里实际上涉及到纷繁复杂的日志体系中的日志转换,大致转换链路过程就是JCL->JUL->slf4j->logback classic->logback以及log4j->slf4j->logback classic->logback