Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a log4j appender that connects with TestNG?

Tags:

log4j

testng

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?

like image 986
Hanno Fietz Avatar asked Oct 15 '09 18:10

Hanno Fietz


People also ask

Does Selenium Grid use log4j?

Log4j is a great logging framework to use in Selenium.

How do I call log4j to my class?

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'.

What is the use of Appender in log4j?

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.


1 Answers

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%
like image 188
yankee Avatar answered Oct 17 '22 15:10

yankee