我正在将我的应用程序中的log4j从1.2版升级到2.12版。我有一段代码需要编写,我不知道该怎么做。
我已经阅读了有关随机访问文件追加器和抽象追加器的信息,但我不知道该使用哪个来创建缺少的目录。
/*
* Created on Jan 10, 2006
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.sbc.swat.logging;
import java.io.Serializable;
import java.io.File;
import java.io.IOException;
//import org.apache.log4j.FileAppender;
//import org.apache.log4j.helpers.LogLog;
//import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.status.StatusLogger;
/**
* @author js5396
*
* log4j Appender that extends FileAppender to create any
* missing directories in the log file path.
*/
//public class MkDirFileAppender extends FileAppender
public class MkDirFileAppender extends AbstractAppender
{
public synchronized void setFile(String fileName,
boolean append,
boolean bufferedIO,
int bufferSize)
throws IOException
{
//LogLog.debug("MkDirFileAppender fileName [" + fileName + "]");
StatusLogger.getLogger().debug("MkDirFileAppender fileName ["+ fileName + "]");
File file = new File(fileName);
File parent = file.getAbsoluteFile().getCanonicalFile().getParentFile();
/*LogLog.debug("MkDirFileAppender parent [" + parent + "] " +
"exist [" + (parent == null ? "null" : parent.exists() + "") + "]");*/
StatusLogger.getLogger().debug("MkDirFileAppender parent ["+ parent + "] "+"exist ["+ (parent == null ? "null": parent.exists()+"")+ "]");
try
{
if (parent != null && !parent.exists())
parent.mkdirs();
}
catch (Throwable e)
{
//LogLog.error("MkDirFileAppender could not create path for: " + fileName, e);
StatusLogger.getLogger().error("MkDirFileAppender could not create path for: "+ fileName, e);
//Fall through, super.setFile will probably fail
}
super.setFile(fileName, append, bufferedIO, bufferSize);
}
}
之前该类扩展了FileAppender并调用了该类的setFile方法,但在log4j2中,FileAppender是最终类,并且不确定扩展抽象附加程序是否是正确的方法。注释的代码是我尝试更改的旧代码。