I use log4j and would like log messages that normally end up in my logging facility to appear in the test reports created by TestNG during my unit tests.
I think that would mean a log4j Appender
which outputs to a TestNG Listener
and an appropriate log4j config in the src/test/resources directory of my Maven project. Is that correct?
It seems fairly easy to write, but is there something I just can pull in via Maven?
Log4j is a great logging framework to use in Selenium.
Step 1 − Download log4j JAR file from https://logging.apache.org/log4j/1.2/download.html and download the Zipped format of the JAR file. Step 2 − Create 'New Java Project' by navigating to the File menu. Step 3 − Enter the name of the project as 'log4j_demo' and click 'Next'.
Appenders. Apache log4j provides Appender objects which are primarily responsible for printing logging messages to different destinations such as consoles, files, sockets, NT event logs, etc. Each Appender object has different properties associated with it, and these properties indicate the behavior of that object.
I had the same problem and eventually coded an appender myself. It is actually quite simple:
Copy the following class:
public class TestNGReportAppender extends AppenderSkeleton {
@Override
protected void append(final LoggingEvent event) {
Reporter.log(eventToString(event));
}
private String eventToString(final LoggingEvent event) {
final StringBuilder result = new StringBuilder(layout.format(event));
if(layout.ignoresThrowable()) {
final String[] s = event.getThrowableStrRep();
if (s != null) {
for (final String value : s) {
result.append(value).append(Layout.LINE_SEP);
}
}
}
return result.toString();
}
@Override
public void close() {
}
@Override
public boolean requiresLayout() {
return true;
}
}
and configure it just like a console appender. E.g. like this:
log4j.appender.testNG=some.package.TestNGReportAppender
log4j.appender.testNG.layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.testNG.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With