Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include Log4j2 messages in TestNG reporting

I would like to have the Log4j2 logging information available in the TestNG reports for all of the test cases.

TestNG uses a special logger class called Reporter.java that keeps track of the log output and saves it in its results XML.

In log4j it was possible to simply create an appender implementation that routes to Reporter and register it.

With the new Logger API in Log4j2 it has been difficult to find information on how to accomplish this. I have some information to get this done using Log4j but not with Log4j2.

like image 402
Praveen Avatar asked Oct 21 '14 09:10

Praveen


Video Answer


1 Answers

From what I can tell you just need to implement a simple Appender. Something like:

@Plugin(name="Reporter", category ="Core", elementType="appender", printObject=true)
public class ReporterAppender extends AbstractAppender {

    private ReporterAppender(final String name, final Layout layout) {
        super(name, null, layout, false);
    }

    @Override
    public void append(final LogEvent event) {
        final Layout<? extends Serializable> layout = getLayout();
        if (layout != null && layout instanceof AbstractStringLayout) {
             Reporter.log(((AbstractStringLayout) layout).toSerializable(event));
        } else {
             Reporter.log(event.getMessage().getFormattedMessage();            }

    @PluginFactory
    public static ReporterAppender createAppender(
        @PluginAttribute("name") @Required(message = "A name for the Appender must be specified") final String name,
        @PluginElement("Layout") Layout<? extends Serializable> layout) {
        return new ReporterAppender(name, layout);
    }
}
like image 117
rgoers Avatar answered Oct 07 '22 13:10

rgoers