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

        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引入了一些新的监听器,从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

Spring Boot Starter Log4j2 是一个用于集成 Log4j2 日志框架的 Spring Boot 启动器。Log4j2 是一个功能强大且灵活的日志记录库,它提供了丰富的功能和配置选项,适用于各种规模的应用程序。 在 Spring Boot 项目中使用 Log4j2,可以通过添加 `spring-boot-starter-log4j2` 依赖来实现。这个启动器会自动配置 Log4j2,并简化了日志配置的过程。 以下是一个简单的示例,展示了如何在 Spring Boot 项目中使用 Log4j2: 1. **添加依赖** 在你的 `pom.xml` 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> ``` 2. **创建 Log4j2 配置文件** 在 `src/main/resources` 目录下创建一个名为 `log4j2.xml` 的配置文件。例如: ```xml <?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/> </Console> </Appenders> <Loggers> <Root level="info"> <AppenderRef ref="Console"/> </Root> </Loggers> </Configuration> ``` 3. **在代码中使用日志** 在你的 Java 类中,你可以这样使用 Log4j2 进行日志记录: ```java import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { private static final Logger logger = LogManager.getLogger(MyApplication.class); public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); logger.info("Application started successfully!"); } } ``` 通过以上步骤,你就可以在 Spring Boot 项目中使用 Log4j2 进行日志记录了。Log4j2 提供了丰富的功能,如异步日志、文件日志、滚动日志等,可以根据需要进行进一步的配置和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值