问题描述
我正在编写测试 Java 库的 Java 代码.该库包含其自己的 log4j2 配置作为分发的一部分.
我想在我的测试代码中使用 log4j2 而不修改库的配置.
有没有办法为我的测试代码设置单独的 log4j2 配置?
这都是作为命令行 Java 运行的,根本没有服务器或 Web 参与.
编辑尝试更清楚:我想要的是能够配置记录器、附加程序等供测试代码使用,并且同时让库代码使用自己的单独配置文件因为它的日志记录.这个想法是在我的测试代码中使用 log4j2,但不必更改库的配置文件.由于库配置文件是库分发的一部分,因此我不想更改它以进行测试.
推荐答案
这可能会有所帮助:
- Log4j2 将首先在类路径中查找 log4j2-test.xml
- 如果找不到该文件,它将在类路径中查找 log4j2.xml
所以一种选择是将库的配置 (log4j2.xml) 复制到 log4j2-test.xml 并将您自己的配置添加到 log4j2-test.xml.
此外,Log4j2 在 XML 配置中支持 XInclude,因此您可以使用它避免在 log4j2-test.xml 中复制库的配置的功能.
问题描述
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.
推荐答案
This may be helpful:
- Log4j2 will first look for log4j2-test.xml in the classpath
- if that file is not found, it will look for log4j2.xml in the classpath
So one option is to copy the library's configuration (log4j2.xml) to log4j2-test.xml and add your own configuration to log4j2-test.xml.
Furthermore, Log4j2 supports XInclude in XML configuration, so you could use that feature to avoid duplicating the library's configuration in your log4j2-test.xml.