If I understand your needs correctly this can be achieved by combining the following:
- using a JUnit method rule which will give you the name of the current method
- creating a Log4j appender at runtime, and configuring it with the name of the method obtained you just obtained
Specifically, you need to create a custom JUnit rule. I chose to extend the TestWatcher
as it seems most appropriate
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
public class TestMethodLogging extends TestWatcher {
private static final String date = new SimpleDateFormat("y-MM-dd")
.format(new Date());
private Logger logger;
@Override
protected void starting(Description description) {
String name = description.getMethodName();
RollingFileAppender a = (RollingFileAppender) Logger.getRootLogger()
.getAppender("rollingFile");
PatternLayout layout = new PatternLayout();
layout.setConversionPattern("%d{dd MMM yyyy HH:mm:ss} %p %t %c - %m%n");
try {
File logDir = new File(a.getFile()).getParentFile();
File logFile = new File(logDir, name + "_" + date);
logger = Logger.getLogger(name);
logger.addAppender(new RollingFileAppender(layout, logFile
.getAbsolutePath()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public Logger getLogger() {
return logger;
}
}
Once you have this you can place it as a rule inside your test class. A rule is simply a field in the test (carrying the @Rule
annotation). In here I called it rule
(not very imaginative, I admit). In order to log from your test method you need to call rule.getLogger()
.
import static org.junit.Assert.assertEquals;
import org.junit.Rule;
import org.junit.Test;
public class MyTest {
@Rule
public TestMethodLogging rule = new TestMethodLogging();
@Test
public void sumOfTwoInts() throws Throwable {
rule.getLogger().error(
"logging to a logger whose name is based on the test method's name");
assertEquals(5, 2 + 3);
}
@Test
public void productOfTwoInts() throws Throwable {
rule.getLogger().error(
"logging to a logger whose name is based on the test method's name");
assertEquals(8, 2 * 4);
}
}
When I run this test it creates these two files under my ~/Desktop/Selenium/AutomationLogs
directory:
productOfTwoInts_2015-05-10
sumOfTwoInts_2015-05-10
The content of the first file looks as follows:
$ cat productOfTwoInts_2015-05-10
10 May 2015 19:59:58 ERROR main productOfTwoInts - logging to a logger whose name is based on the test method's name
10 May 2015 20:01:22 ERROR main productOfTwoInts - logging to a logger whose name is based on the test method's name
10 May 2015 20:01:24 ERROR main productOfTwoInts - logging to a logger whose name is based on the test method's name