默認狀況下,只要把log4j配置文件放在 CLASSPATH 環境變量所指定的目錄, JAVA 啓動時會制動加載。實際項目中常常須要把配置文件與打包分離,方便修改,因此須要自定義配置文件加載地址。web
採用spring mvc框架時須要通常在web.xml裏配置spring
<context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>6000</param-value> </context-param>
採用spring boot輕量級框架後,大部分自定義配置都放在application.properties裏了mvc
logging.config=file:config/log4j2.xm
本節爲本文重點,發現不少人離了框架就不知道該怎麼寫代碼了。app
鍵值對格式框架
PropertyConfigurator.config(filepath)
XML 格式spa
DOMConfigurator.config(filepath)
log4j2裏通常不建議使用properties文件,而是使用xml文件。log4j2的版本里自定義配置文件加載地址的接口改成Configurator.initialize了code
static { try { ConfigurationSource source; String relativePath = "config" + System.getProperty("file.separator") + "log4j2.xml"; File log4jFile = new File( System.getProperty("user.dir") + System.getProperty("file.separator") + relativePath); if (log4jFile.exists()) { source = new ConfigurationSource(new FileInputStream(log4jFile), log4jFile); Configurator.initialize(null, source); } } catch (IOException e) { e.printStackTrace(); } }