![f0b9bfae7afc8ec057a3b9a976bf734f.png](https://img-blog.csdnimg.cn/img_convert/f0b9bfae7afc8ec057a3b9a976bf734f.png)
在没有设置自动加载log4j.xml的时候,一般我们需要这么处理
static void initLogger()
{
System.out.println("configurating log4j with log4j xml");
DOMConfigurator.configure("log4j.xml");
logger = Logger.getLogger("name");
}
此时如果在eclipse中,log4j.xml是与src工程目录并列的位置;
如果工程编译成jar包,log4j.xml也是jar包在同一目录下使用,不会包含在jar包当中;
我们其实还可以将log4j的读取过程通过log4j的自动加载机制完成,省去第一行代码
DOMConfigurator.configure("log4j.xml");;
我们只需要把log4j.xml的位置挪动下,挪动到src代码目录里层即可;
下面介绍下一般方式下的加载原理:
org.apache.log4j.xml.DOMConfigurator.java源码如下
/**
A static version of {@link #doConfigure(String, LoggerRepository)}.
*/
static
public
void configure(String filename) throws FactoryConfigurationError
{
new DOMConfigurator().doConfigure(filename,
LogManager.getLoggerRepository());
}
public
void doConfigure(final String filename, LoggerRepository repository)
{
ParseAction action = new ParseAction()
{
public Document parse(final DocumentBuilder parser)
throws SAXException, IOException
{
return parser.parse(new File(filename));
}
public String toString()
{
return "file [" + filename + "]";
}
};
doConfigure(action, repository);
}
private final void doConfigure(final ParseAction action,
final LoggerRepository repository)
throws FactoryConfigurationError
{
DocumentBuilderFactory dbf = null;
this.repository = repository;
try {
LogLog.debug("System property is :"+
OptionConverter.getSystemProperty(dbfKey, null));
dbf = DocumentBuilderFactory.newInstance();
LogLog.debug("Standard DocumentBuilderFactory search succeded.");
LogLog.debug("DocumentBuilderFactory is: "+dbf.getClass().getName());
} catch(FactoryConfigurationError fce) {
Exception e = fce.getException();
LogLog.debug("Could not instantiate a DocumentBuilderFactory.", e);
throw fce;
}
try {
dbf.setValidating(true);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
docBuilder.setErrorHandler(new SAXErrorHandler());
docBuilder.setEntityResolver(new Log4jEntityResolver());
Document doc = action.parse(docBuilder);
parse(doc.getDocumentElement());
} catch (Exception e) {
if (e instanceof InterruptedException ||
e instanceof InterruptedIOException)
{
Thread.currentThread().interrupt();
}
// I know this is miserable...
LogLog.error("Could not parse "+ action.toString() + ".", e);
}