java 使用 log4j 以编程方式创建不同的日志文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1666121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically creating different log files using log4j
提问by Alexis
I have an automated integration test harness and would like to streamline the logging (which is implemented using log4j)
我有一个自动化集成测试工具,并希望简化日志记录(使用 log4j 实现)
I have a number of high-level tests, each with an id and require a separatelog file per test. As the tests are created randomly the ids are not known until runtime.
我有许多高级测试,每个测试都有一个 id,并且每个测试都需要一个单独的日志文件。由于测试是随机创建的,因此直到运行时才知道 id。
Therefore I would like to ensure that logging within each high-level test is written out to the log file for that test.
因此,我想确保将每个高级测试中的日志记录写出到该测试的日志文件中。
I don't want to create custom log levels, neither do I want to have logging sent to all appenders.
我不想创建自定义日志级别,也不想将日志发送到所有 appender。
Does anyone know a way of doing this?
有谁知道这样做的方法?
回答by skaffman
You can easily invoke log4j's API programmatically, e.g.
您可以轻松地以编程方式调用 log4j 的 API,例如
FileAppender appender = new FileAppender();
// configure the appender here, with file location, etc
appender.activateOptions();
Logger logger = getRootLogger();
logger.addAppender(appender);
The loggercan be the root logger as in this example, or any logger down the tree. Your unit test can add its custom appender during steup, and remove the appender (using removeAppender()) during teardown.
所述logger可根记录器如在本例中,或向下树中的任何记录程序。您的单元测试可以在 steup 期间添加其自定义 appender,并removeAppender()在拆卸期间删除 appender(使用)。

