How would you implement so that each test class log is output to a separate file?

Using Java with TestNG or JUnit, if you want to register some information collected during the test into a file and each test class (for example, TestClass1.class ) save a separate output to the file, named after the class:

TestClass1.log 

How would you implement this? I know that log4j can write the class name in the line "per line" of output in one file, but I want the outputs for each class to be in separate files. In addition, log4j can write output to different files based on the name of the package. None of these solutions are what I'm looking for because I want hundreds of tests to create hundreds of log files .

0
source share
1 answer

Using Log4J 1.x, you will have to manually create a Logger instance in each class, providing a unique file name for each test, using a combination of the set name and class name (assuming each set has a unique name).

For example, in the setUp() method of the test class, specify the log file name:

 String logFilename = context.getSuite().getName() + "_" + this.getClass().getSimpleName(); 

Then, in each class used by the test, manually create a logger instance and specify the name of the log file that 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 passing the file name to all the classes used in the test.

The best decision:

If you can upgrade to Log4J 2, it supports writing to separate log files using ThreadContext : http://logging.apache.org/log4j/2.x/faq.html#separate_log_files

I also found this blog post suggesting to use LOGBack and its contextual diagnostic context: http://www.nullin.com/2010/07/28/logging-tests-to-separate-files/

0
source

Source: https://habr.com/ru/post/1205169/


All Articles