在做项目时,发现自定义的logback的Appender的start方法执行的时机非常的靠前,在Spring框架注入bean之前就完成了。
问了一下公司的架构师,start方法的执行时机有两类情况,第一种是服务启动的时候,也就是刚刚提到的时机。
第二种是服务触发了logback的刷新机制,找到了spring-cloud-commons项目下的源码,如下:
private void reinitializeLoggingSystem(ConfigurableEnvironment environment,
String oldLogConfig, LogFile oldLogFile) {
Map<String, Object> props = Binder.get(environment)
.bind("logging", Bindable.mapOf(String.class, Object.class)).orElseGet(Collections::emptyMap);
if (!props.isEmpty()) {
String logConfig = environment.resolvePlaceholders("${logging.config:}");
LogFile logFile = LogFile.get(environment);
LoggingSystem system = LoggingSystem
.get(LoggingSystem.class.getClassLoader());
try {
ResourceUtils.getURL(logConfig).openStream().close();
// Three step initialization that accounts for the clean up of the logging
// context before initialization. Spring Boot doesn't initialize a logging
// system that hasn't had this sequence applied (since 1.4.1).
system.cleanUp();
system.beforeInitialize();
system.initialize(new LoggingInitializationContext(environment),
logConfig, logFile);
}
catch (Exception ex) {
PropertySourceBootstrapConfiguration.logger
.warn("Logging config file location '" + logConfig
+ "' cannot be opened and will be ignored");
}
}
}
Environment由Spring的环境配置注入,是Profile和PropertyResolver的组合。
执行上述方法即可完成logback的刷新,调用start方法。