问题
Using Java, with either TestNG or JUnit, if you wanted to log some information gathered during a test to a file, and have each test class (such as TestClass1.class) keep a separate output file named after the class like so:
TestClass1.log
How would you implement this kind of thing? I know log4j can log the class name in a 'per line' of output in a single file but I want outputs for each class to be in separate files. Also, log4j can log output to different files based on package name. Neither of those solutions is what I am looking for because I want hundreds of tests to create hundreds of log files.
回答1:
Using Log4J 1.x, you would have to manually instantiate the Logger in each class, providing a unique file name for each test using a combination of the suite name and class name (assuming each suite has a unique name).
For example in the setUp()
method of the test class, define the name of the log file:
String logFilename = context.getSuite().getName() + "_" + this.getClass().getSimpleName();
Then in each class used by the test, manually instantiate the logger and provide the name of the log file you want to use:
public class SomeClass {
private Logger log = null;
public SomeClass(String logFilename) {
log = Logger.getLogger(logFilename);
}
But this solution is not very elegant, it requires to pass the file name to all the classes used in the test.
A better solution:
If you can upgrade to Log4J 2, it supports writing to separate log files using a ThreadContext
:
http://logging.apache.org/log4j/2.x/faq.html#separate_log_files
I also found this blog post that suggests using LOGBack and its Mapped Diagnostic Context: http://www.nullin.com/2010/07/28/logging-tests-to-separate-files/
来源:https://stackoverflow.com/questions/25148492/how-would-you-implement-so-each-test-class-logs-output-to-a-separate-file