1.Springboot在启动的时候初始化日志监听器
org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener
2.日志监听器的初始化方法
protected void initialize(ConfigurableEnvironment environment, ClassLoader classLoader) {
(new LoggingSystemProperties(environment)).apply();
this.logFile = LogFile.get(environment);
if (this.logFile != null) {
this.logFile.applyToSystemProperties();
}
this.loggerGroups = new LoggerGroups(DEFAULT_GROUP_LOGGERS);
this.initializeEarlyLoggingLevel(environment);
this.initializeSystem(environment, this.loggingSystem, this.logFile);
this.initializeFinalLoggingLevels(environment, this.loggingSystem);
this.registerShutdownHookIfNecessary(environment, this.loggingSystem);
}
this.logFile = LogFile.get(environment)
这里获取日志文件路径
3.LogFile类
public class LogFile {
public static final String FILE_NAME_PROPERTY = "logging.file.name";
public static final String FILE_PATH_PROPERTY = "logging.file.path";
private final String file;
private final String path;
LogFile(String file) {
this(file, (String)null);
}
LogFile(String file, String path) {
Assert.isTrue(StringUtils.hasLength(file) || StringUtils.hasLength(path), "File or Path must not be empty");
this.file = file;
this.path = path;
}
public void applyToSystemProperties() {
this.applyTo(System.getProperties());
}
public void applyTo(Properties properties) {
this.put(properties, "LOG_PATH", this.path);
this.put(properties, "LOG_FILE", this.toString());
}
private void put(Properties properties, String key, String value) {
if (StringUtils.hasLength(value)) {
properties.put(key, value);
}
}
public String toString() {
return StringUtils.hasLength(this.file) ? this.file : (new File(this.path, "spring.log")).getPath();
}
public static LogFile get(PropertyResolver propertyResolver) {
String file = propertyResolver.getProperty("logging.file.name");
String path = propertyResolver.getProperty("logging.file.path");
return !StringUtils.hasLength(file) && !StringUtils.hasLength(path) ? null : new LogFile(file, path);
}
}
这里会自动从application.propertie或者application.yml中获取logfile的name和path
4.LogFile方法get(静态方法)
public static LogFile get(PropertyResolver propertyResolver) {
String file = propertyResolver.getProperty("logging.file.name");
String path = propertyResolver.getProperty("logging.file.path");
return !StringUtils.hasLength(file) && !StringUtils.hasLength(path) ? null : new LogFile(file, path);
}
- get方法首先从springboot配置文件中获取filename和fileapath
- 然后判断是否获取成功,如果都没有获取成功,返回null
- 那么springboot就不会将日志写到文件
- 如果获取一个值或全部获取就返回 一个LogFile,通过构造函数传入filename和filepath
5.LogFile核心逻辑toString()
toString是Object的方法,java中所有类都是Object的子类,LogFile重写了toString方法
public String toString() {
return StringUtils.hasLength(this.file) ? this.file : (new File(this.path, "spring.log")).getPath();
}
判断filename是否有值:
- 如果有值直接返回filename
- 否则返回路径+spring.log
6.结论
也就是说,如果我们配置了filename和filepath,那么我们的日志文件名就是filename,路径会忽略;
如果我们只配置了路径,那么我们的日志文件名默认是spring.log,并且springboot会自动帮我们创建文件夹
所以,如果我们想指定自己日志的路径和名称,那么我们的路径里文件夹必须自己创建