By default, as long as the log4j configuration file is placed in the directory specified by the CLASSPATH environment variable, JAVA will be loaded when it starts. In actual projects, it is often necessary to separate configuration files from packaging to facilitate modification, so it is necessary to customize the load address of configuration files.
SpringMvc
When using the spring mvc framework, it needs to be generally configured in web.xml
<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
After using the spring boot lightweight framework, most of the custom configurations are placed in application.properties
logging.config=file:config/log4j2.xm
frameless
This section is the focus of this article. It is found that many people do not know how to write code without the framework.
log4j
key-value format
PropertyConfigurator.config(filepath)
XML format
DOMConfigurator.config(filepath)
log4j2
It is generally not recommended to use properties files in log4j2, but to use xml files. In the log4j2 version, the interface of the custom configuration file load address has been changed to Configurator.initialize
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();
}
}