本文介绍了使用log4j以编程方式创建不同的日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自动化集成测试工具,并希望简化日志记录(使用log4j实现)

I have an automated integration test harness and would like to streamline the logging (which is implemented using log4j)

我有许多高级测试,每个测试带有id并且每次测试需要单独的日志文件。由于测试是随机创建的,因此直到运行时才知道id。

I have a number of high-level tests, each with an id and require a separate log file per test. As the tests are created randomly the ids are not known until runtime.

因此我想确保将每个高级测试中的日志记录写入日志文件对于该测试。

Therefore I would like to ensure that logging within each high-level test is written out to the log file for that test.

我不想创建自定义日志级别,也不想将日志记录发送到所有appender。

I don't want to create custom log levels, neither do I want to have logging sent to all appenders.

有没有人知道这样做的方法?

Does anyone know a way of doing this?

推荐答案

您可以通过编程方式轻松调用log4j的API,例如

You can easily invoke log4j's API programmatically, e.g.

FileAppender appender = new FileAppender();
// configure the appender here, with file location, etc
appender.activateOptions();

Logger logger = getRootLogger();
logger.addAppender(appender);

logger 可以是根记录器在此示例中,或在树下的任何记录器。您的单元测试可以在steup期间添加其自定义appender,并在拆除期间删除appender(使用 removeAppender())。

The logger can 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.

这篇关于使用log4j以编程方式创建不同的日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 04:32