如何在Spring5和Tomcat8中加载外部log4j日志配置(Log4jConfigListener)

如何在Spring5和Tomcat8中加载外部log4j日志配置(Log4jConfigListener),spring,tomcat,logging,log4j,Spring,Tomcat,Logging,Log4j,我有一个JavaSpring5应用程序,部署到Tomcat8.5.15。java应用程序包含log4j框架和(默认)配置文件“log4j.properties” 在某些情况下,我想加载一个外部log4j文件来覆盖应用程序中打包的文件,这可能吗 您可以在使用Spring的“Log4jConfigListener”之前做到这一点。是的,您可以通过编写少量代码来使用它的外部配置设置 // import org.apache.logging.log4j.core.LoggerContext; Logg

我有一个JavaSpring5应用程序,部署到Tomcat8.5.15。java应用程序包含log4j框架和(默认)配置文件“log4j.properties”

在某些情况下,我想加载一个外部log4j文件来覆盖应用程序中打包的文件,这可能吗


您可以在使用Spring的“Log4jConfigListener”之前做到这一点。

是的,您可以通过编写少量代码来使用它的外部配置设置

// import org.apache.logging.log4j.core.LoggerContext;

LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
File file = new File("path/to/a/different/log4j2.xml");

// this will force a reconfiguration
context.setConfigLocation(file.toURI());
参考:

如果您不想
*.xml
,则可以使用其他类型,如
JSON
YAML
属性


 1. Log4j will inspect the "log4j.configurationFile" system property and, if set, will attempt to load the configuration using the ConfigurationFactory that matches the file extension. Note that this is not restricted to a location on the local file system and may contain a URL.
 2. If no system property is set the properties ConfigurationFactory will look for log4j2-test.properties in the classpath.
 3. If no such file is found the YAML ConfigurationFactory will look for log4j2-test.yaml or log4j2-test.yml in the classpath. 
 4. If no such file is found the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath. 
 5. If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath. 
 6. If a test file cannot be located the properties ConfigurationFactory will look for log4j2.properties on the classpath. 
 7. If a properties file cannot be located the YAML ConfigurationFactory will look for log4j2.yaml or log4j2.yml on the classpath.
 8. If a YAML file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.
 9. If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.
 10. If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.


参考资料:

@Jojje我没有试过,但log4j和log4j2几乎相同,所以我认为它会起作用。请访问并搜索“示例配置”,并阅读您的条件。我希望它能正常工作,如果可以的话,从log4j迁移log4j2也是一个不错的选择。