8

I am writing Java code that tests a Java library. The library includes its own log4j2 configuration as part of the distribution.

I would like to use log4j2 in my test code without modifying the library's configuration.

Is there a way to have a separate log4j2 configuration for my test code?

This is all running as command-line Java, no servers or web involvement at all.

EDIT to try to be more clear: What I want is to be able to configure loggers, appenders, etc for the test code to use , and at the same time have the library code use its own separate configuration file for its logging. The idea is to use log4j2 in my test code, but without having to change the library's configuration file. Since the library configuration file is part of the library's distribution, I don't want to change it for testing.

4

7 回答 7

7

这可能会有所帮助:

  • Log4j2 将首先在类路径中查找 log4j2-test.xml
  • 如果找不到该文件,它将在类路径中查找 log4j2.xml

因此,一种选择是将库的配置 (log4j2.xml) 复制到 log4j2-test.xml 并将您自己的配置添加到 log4j2-test.xml。

此外,Log4j2在 XML 配置中支持 XInclude,因此您可以使用该功能来避免在 log4j2-test.xml 中复制库的配置。

于 2014-04-22T06:16:22.707 回答
6

Log4j2 支持完全符合您要求的“复合配置”。您需要做的就是在log4j.configurationFile属性中提供多个文件的路径。这可以从命令行传递或添加到log4j2.component.properties应用程序的文件中。

参考: https ://logging.apache.org/log4j/2.x/manual/configuration.html#CompositeConfiguration https://logging.apache.org/log4j/2.x/manual/configuration.html#SystemProperties

于 2017-09-23T02:19:30.033 回答
3

您可以尝试通过两个步骤来解决您的问题

  • 使用您的自定义名称创建您自己的配置文件(例如:xyz.properties/.xml)
  • 您必须将以下行添加到您的 java 运行时命令

cmd> java -Dlog4j.configuration=location/xyz.properties

如果您使用不同的名称进行配置而不是 log4j.properties/.xml 文件,则需要在运行时通过上述命令配置该文件以获取更多信息,请查看此处..

于 2014-04-22T06:49:20.140 回答
0

要使用多个配置文件,必须根据环境进行设置。

例如:

if (env.equals("DEV")) {
 setConfigFile("log4j2-dev.xml");
}

public static void setConfigFile(String logConfigFile) {
        File file = new File(logConfigFile);
        LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
        context.setConfigLocation(file.toURI());
    }
于 2020-08-14T17:53:14.583 回答
0

将备用 XML 文件用于 log4j2.xml 的正确格式:

java -Dlog4j.configurationFile=./location/log4j2-custom.xml

假设./location/log4j2-custom.xml存在并且是本次运行中替换 log4j2.xml 的新 XML

请参阅: https ://github.com/kamalcph/Log4j2Example/blob/master/src/main/java/in/co/nmsworks/log4j2/examples/CompositeConfigurationExample.java

于 2019-04-17T20:37:47.363 回答
0
first configure application.yaml file
spring:
  profiles:
    active: dev

---
spring:
  message: running in the dev profile    //just to output the message in the log
  profiles: dev
logging.config: classpath:log4j2-dev.xml

---
spring:
  profiles: prod
logging.config: classpath:log4j2-prod.xml



and create these similar files in your classpath
* log4j2-dev.xml
* log4j2-prod.xml
于 2020-09-19T14:05:44.453 回答
0

引用https://logging.apache.org/log4j/2.x/manual/configuration.html声明您可以在 log4j2.configurationFile 属性下添加多个逗号分隔的文件。

于 2019-05-14T19:16:35.167 回答