先上代码:
public class TemplateUtil {
private static RuntimeInstance ri = new RuntimeInstance();public static Template getTemplate(String relativePath, String fileName) {
String root = TemplateUtil.class.getClassLoader().getResource("").toString();
String path = root + relativePath;
path = path.substring(5);
if (!ri.isInitialized()) {
//ri.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
ri.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,path);
ri.init();
}
Template template = ri.getTemplate(fileName);
return template;
}
}
ri.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
加上这一句会不打印日志,不加会打印日志,默认是到velocity.log
看RuntimeInstance类的init
public synchronized void init()
{
if (!initialized && !initializing)
{
log.debug("Initializing Velocity, Calling init()...");
initializing = true;
log.trace("*******************************************************************");
log.debug("Starting Apache Velocity v1.7 (compiled: 2010-11-19 12:14:37)");
log.trace("RuntimeInstance initializing.");
initializeProperties();
initializeLog();
initializeResourceManager();
initializeDirectives();
initializeEventHandlers();
initializeParserPool();
initializeIntrospection();
initializeEvaluateScopeSettings();
/*
* initialize the VM Factory. It will use the properties
* accessable from Runtime, so keep this here at the end.
*/
vmFactory.initVelocimacro();
log.trace("RuntimeInstance successfully initialized.");
initialized = true;
initializing = false;
}
}
可以看到在调用initializeLog() 之前,已经有了log.debug
那么这是怎么实现的呢,所以我就很费解,就跟源码。
可以看到Log log = new Log()
new Log()里面setLogChute(new HoldingLogChute());
这个HoldingLogChute是一个代理,把记录的log放到一个Vector中:
public synchronized void log(int level, String message)
{
if (!transferring)
{
Object[] data = new Object[2];
data[0] = new Integer(level);
data[1] = message;
pendingMessages.addElement(data);
}
}
等到initializeLog之后,HoldingLogChute会把记录的logtransfoer给初始化之后的log
public synchronized void transferTo(LogChute newChute)
{
if (!transferring && !pendingMessages.isEmpty())
{
// let the other methods know what's up
transferring = true;
// iterate and log each individual message...
for(Iterator i = pendingMessages.iterator(); i.hasNext();)
{
Object[] data = (Object[])i.next();
int level = ((Integer)data[0]).intValue();
String message = (String)data[1];
if (data.length == 2)
{
newChute.log(level, message);
}
else
{
newChute.log(level, message, (Throwable)data[2]);
}
}
}
}