Daredevi1 Daredevi1 - 28 days ago 18
Java Question

Java - Logback to display testcase name

I am using Logback in my Selenium Webdriver project and I've reached a bit of a roadblock. I've search online but not been able to find the answer.

I am trying to find a way which allows me to get the testcase name (testGoogleWebsite) once inside the

setup()
method. So instead of just printing "Starting test" it prints out "Starting test - testGoogleWebsite"

I know I can do
LOG.debug("testGoogleWebsite");
on the first line of each test, but wanted to know if there's a better way.

My Test:

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


@BeforeTest
public void setup() throws FileNotFoundException {
LOG.debug("Starting test - ");
driver = new ChromeDriver();
}

@AfterTest
public void tearDown(){
LOG.debug("End of test");
}


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

I think you are talking about logging your testacse name (as testGoogleWebsite is a testcase name I see). To do this you can put your LOG.debug("Starting test - "); in beforeMethod.

Code snippet

@BeforeMethod
public void beforeMethod(Method method) {
  LOG.debug("Starting test - " + method.getName(););
}

This will log your each and every testcase name as you wanted.