0

I have a java project which uses log4j as a logger. The requirement is to have the test case name printed in the log file.

There are multiple tests in one class And the project supports parallel execution as well. A logger instance is created for each test.

I used system.Setproprty to associate my current logger instance with a the test case name. Following is my log4j.properties file :-

log4j.appender.logFileAppender.layout.ConversionPattern=%d{yyyy/MM/dd HH:mm:ss} [%t] ${testCaseName} %5p (%F:%L) - %m%n
log4j.appender.logFileAppender.Append=false
log4j.appender.logFileAppender.file=./log/UITest.log

And the runtime variable ${testCaseName} is set while creating a new instance of logger file as follows :-

public Logger log; 
public synchronized Logger initializeLogger(String testName) 
    { 
    log = LoggerFactory.getLogger(testName);      
    System.setProperty("testCaseName", testName);             
    PropertyConfigurator.configure(log4jPropertiesFilePath); 
    return log; 
    } 

The above looger instance creation method is called in a @BeforeMethod.

Currently the logger file is printing the test name of the last test in a class (In non-parallel ans parallel execution mode)

Kindly help me identify the issue due to which multiple test cases are not having their testcase name printed in the log file.

Navarasu
  • 6,991
  • 2
  • 19
  • 31
bucky barns
  • 165
  • 12
  • I think log file is initialized only once during test case run, so only 1 test name is printed. Did you tried Java `reflection` parameter `Method` or `testng` annotation `ITestResult`. You can check this link https://stackoverflow.com/questions/2952202/how-do-i-get-the-name-of-the-test-method-that-was-run-in-a-testng-tear-down-meth – Amit Jain Oct 29 '18 at 11:51
  • Thanks for the reply Amit. But I am calling the "initializeLogger" method before each test. Also when 2 tests in a class are run, my log file has the logs with the name of second test case. I use the ITestResult to pass the testName as parameter to initialize logger, it works fine. The only problem is associating the testCaseName to different logger instances. – bucky barns Oct 29 '18 at 11:55
  • Anyone aware for the solution of this issue ? – bucky barns Nov 02 '18 at 06:37

1 Answers1

0

try adding this to your test

  @Rule 
  public TestName testName = new TestName();

  @Before 
  public void printTestName() {
     System.out.println("Running ==> " + testName.getMethodName()); 
  }
mahbuhs_redoc
  • 1,255
  • 1
  • 11
  • 25
RamiaSY
  • 1
  • 1
  • Can you please add some explanation as well along with your code so that it can help Original Poster(OP) of the question properly. Welcome to stackoverflow, please follow https://stackoverflow.com/help/how-to-answer. – mahbuhs_redoc Feb 21 '21 at 05:00