之前在“velocity源码分析:velocity初始化”文章中粗略地介绍了velocity整体的初始化过程,包括各个系统的初始化,本文主要介绍日志系统初始化。
日志系统类图:
概要:
1.调用:velocity源码中这种封装方式我个人是比较赞同的,也是相当容易扩展,对于日志系统之外的内容只需要关注Log(进行日志操作),LogManager(日志系统初始化)即可;
2.日志系统扩展:目前该套代码包含了大部分的日志记录方式,假设以后新增一种记录方式,只要添加对应的Chute并实现LogChute接口即可;
3.日志记录方式扩展:LogDisplayWrapper已经很好的实现了扩展,对于日志,新增一些标识,该类完全足够;
说明:
Velocity在初始化时调用RuntimeInstance.initializeLog()进行日志系统的初始化。
该方法调用如下代码,传入日志系统接口类和配置信息初始化。
LogManager.updateLog(this.log, this);
方法具体实现:
public static void updateLog(Log log, RuntimeServices rsvc) throws Exception
{
// create a new LogChute using the RuntimeServices
LogChute newLogChute = createLogChute(rsvc);
LogChute oldLogChute = log.getLogChute();
// pass the new LogChute to the log first,
// (if the old was a HoldingLogChute, we don't want it
// to accrue new messages during the transfer below)
log.setLogChute(newLogChute);
// If the old LogChute was the pre-Init logger,
// dump its messages into the new system.
if (oldLogChute instanceof HoldingLogChute)
{
HoldingLogChute hlc = (HoldingLogChute)oldLogChute;
hlc.transferTo(newLogChute);
}
}
1.创建LogChute:
LogChute的创建采用反射的方式初始化配置文件中定义
runtime.log.logsystem
和
runtime.log.logsystem.class
的内容。看看一下velocity自带的配置文件:
runtime.log.logsystem.class = org.apache.velocity.runtime.log.Log4JLogChute,org.apache.velocity.slf4j.Slf4jLogChute,org.apache.velocity.runtime.log.CommonsLogLogChute,org.apache.velocity.runtime.log.ServletLogChute,org.apache.velocity.runtime.log.JdkLogChute
# ---------------------------------------------------------------------------
# This is the location of the Velocity Runtime log.
# ----------------------------------------------------------------------------
runtime.log = velocity.log
默认不配置runtime.log.losystem,但配置了对应class列表,该列表的初始化顺序是:
org.apache.velocity.runtime.log.Log4JLogChute,
org.apache.velocity.slf4j.Slf4jLogChute,
org.apache.velocity.runtime.log.CommonsLogLogChute,
org.apache.velocity.runtime.log.ServletLogChute,org.
apache.velocity.runtime.log.JdkLogChute
默认初始化log4日志。 当一个日志系统能获取后就丢弃其他信息2.替换日志系统:
RuntimeInstance代码中有成员变量:private Log log = new Log();初始化默认的日志系统。
Log()代码:
public Log()
{
setLogChute(new HoldingLogChute());
}
可以发现,RuntimeInstance在初始化日志系统之前,默认使用HoldingLogChute()。
再看初始化LogManager.updateLog方法,该方法在初始化log系统之后先把原先的日志信息记录下来,如果原先采用的是HoldingLogChute,则把原先记录的信息写到新的日志系统中。
这是个很简单但很有用的日志系统信息交换的方式。
至此:RuntimeInstance中:
private Log log = new Log();
初始化好了,至于private ExtendedProperties overridingProperties = null;
在调用时作初始化