Daredevi1 Daredevi1 - 27 days ago 14
Java Question

Java - Logback to display status of run (passed / failed)

I am using Logback in my Selenium Webdriver project and I'm trying to find a way to log the status (whether the test passed or failed) right at the end of the test, so when looking through the logs you know which test has failed.

I've got an

afterMethod
where I currently log "testGoogleWebsite has finished", but want to get "testGoogleWebsite has failed" or "testGoogleWebsite has passed".

My Test:

@Test
public void testGoogleWebsite() {
openGoogleWebsite();
searchForStackOverflow();
clickOnStackOverflowLink();
}


@AfterMethod
public void afterMethod(Method method){
LOG.debug(method.getName() + " has finished");
}


My logback file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

<property name="DEV_HOME" value="target/Logs" />

<appender name="FILE-AUDIT" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${DEV_HOME}/debug.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</encoder>

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>${DEV_HOME}/archived/debug.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>

</appender>

<logger name="com.test" level="debug" additivity="false">
<appender-ref ref="FILE-AUDIT" />
</logger>

<root level="debug">
<appender-ref ref="FILE-AUDIT" />
</root>

</configuration>

Answer
@AfterMethod
public void afterMethod(ITestResult result)
{

    String tcName = result.getName();
    if(result.getStatus() == ITestResult.SUCCESS)
    {

        //Do something here
        LOG.debug(tcName  + " has passed");
    }

    else if(result.getStatus() == ITestResult.FAILURE)
    {
         //Do something here
        LOG.debug(tcName  + " has failed");

    }

     else if(result.getStatus() == ITestResult.SKIP ){

       LOG.debug(tcName  + " has skipped");
    }
}