I am trying to integrate Log4J into my tests that use TestNG, I have added a logger, but when I try to use it I don't get any output.
I am using the JDK 18, latest stable TestNG and Log4J core.
public abstract class DemoAutomationTest extends AbstractTest {
private Logger logger = null;
@BeforeSuite
@Override
protected void suiteSetup() {
String testName = this.getClass().getCanonicalName();
this.logger = LogManager.getLogger(testName);
this.logger.info("Test info");
}
}
Any help would be appreciated, I have looked this up here, on Stack Overflow and can't find an answer.
CodePudding user response:
The beauty of log4j (or other logging frameworks) is that once you are happy with the code you turn off logging without modifying the code again. You do not remove the log statements but configure the framework to not output the messages.
Now in your case it is likely you forgot to configure log4j. An easy way to do so is to add a file called log4j2.xml
to your classpath. Start off with this content:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Logger level="info" name="org.apache.mina.filter.codec.ProtocolCodecFilter"/>
<Root level="TRACE">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
CodePudding user response:
for the tests i have it:
static ListAppender<ILoggingEvent> getLogAppender(final Class<?> clazz) {
final var logger = (Logger) LoggerFactory.getLogger(clazz);
final var appender = new ListAppender<ILoggingEvent>();
appender.start();
logger.addAppender(appender);
return appender;
}
than i use it like:
private ListAppender<ILoggingEvent> logAppender = TestUtils.getLogAppender(MyClass.class);
assertEquals(1, logAppender.list.size());
assertEquals("Code: 401, Response body: ", logAppender.list.get(0).getFormattedMessage());