Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing Log4j output when executing TestNG tests

Tags:

java

log4j

testng

I am executing TestNG tests , and the logging output is set to DEBUG, so in case of a failure I can get to inspect exactly what goes wrong.

The problem is that the output is extremely verbose, and it's bothering everyone when it runs . I would like to capture all Log4J logging events - which is easy - and only print them when the test fails. Also, I need to take into account @Before/@After methods and also print output for them.

Assuming that I already have a List of Log4J LoggingEvents , how can I print those only when the Test/After/Before methods fail?

like image 227
Robert Munteanu Avatar asked Jul 14 '10 15:07

Robert Munteanu


2 Answers

Use Reporter.log(str) to log the message on the report.

@AfterMethod
public void printLOGonFailure(ITestResult result) {
    if (result.getStatus() == ITestResult.FAILURE) {
        String  str = getLog();
        Reporter.log(str);
    }
}
like image 173
Vinayak Avatar answered Sep 19 '22 01:09

Vinayak


This site has a explanation on how to do it.. I copied the code part here in case the link goes dead.

Logger.getLogger(this.getClass())
log4j.rootLogger=ERROR,TESTAPPENDER
log4j.appender.TESTAPPENDER=com.my.fantastic.MockedAppender
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class FooTest {
    private Appender appenderMock;
    @Before
    public void setupAppender() {
        appenderMock = mock(Appender.class);
        Logger.getRootLogger().addAppender(appenderMock);
    }
    @After
    public void removeAppender() {
        Logger.getRootLogger().removeAppender(appenderMock);
    }
    @Test
    public void testMethod()  {
        doStuffThatCausesLogging();
        verify(appenderMock).doAppend((LoggingEvent) anyObject());
    }
}

ArgumentCaptor arguments = ArgumentCaptor.forClass(LoggingEvent.class);
verify(appenderMock).doAppend(arguments.capture());

assertThat(arguments.getValue().getLevel(), is(Level.WARN));

like image 24
Sardathrion - against SE abuse Avatar answered Sep 20 '22 01:09

Sardathrion - against SE abuse