我在TestNG中并行运行了一些WebDriver测试。我希望能够将日志记录日志到在目录结构中运行的每个测试的单独文件中,如下所示:
targetlogsTestNGSuiteName(SuiteStartTime)
Test1ClassName.TestMethod1 (TestStartTime).log
Test1ClassName.TestMethod2 (TestStartTime).log
等。
使用 Log4j 和 SLF4j 是否可以为每个单独的 TestNG 测试创建一个单独的日志文件?
我尝试使用 RollingFileAppender,但它看起来不像是为让单独的实例为单独的日志文件运行而设计的,就像我在这里尝试做的那样。
我收到错误
ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.appender.RollingFileAppender for element RollingFile.
Unable to create Appender of type RollingFile.
日志4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Routing name="Routing">
<Routes pattern="$${ctx:ROUTINGKEY}">
<Route>
<RollingFile name="Rolling-${ctx:ROUTINGKEY}"
fileName="target/logs/${ctx:suiteTimestamp}/${ctx:testName} (${ctx:testStartTime}).log"
filePattern="target/logs/${ctx:testname} ${ctx:testStartTime}_%i.log.gz">
<PatternLayout>
<pattern>%d{HH:mm:ss.SSS} [%t] %p %c{3} - %m%n</pattern>
</PatternLayout>
<Policies> <!-- 6 hour rollover-->
<TimeBasedTriggeringPolicy interval="6" modulate="true"/>
<SizeBasedTriggeringPolicy size="10 MB"/>
</Policies>
</RollingFile>
</Route>
</Routes>
</Routing>
</Appenders>
<Loggers>
<Logger name="james.log" level="debug" additivity="false">
<AppenderRef ref="Routing"/>
</Logger>
</Loggers>
</Configuration>
伐木杰克.java
package james.log;
import james.util.ConcurrentDateFormatAccess;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.ITestContext;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
/**
* @author james.affleck
*/
public class LumberjackTest {
private static final Logger logger = LoggerFactory.getLogger(LumberjackTest.class);
private static ThreadLocal<String> methodLogName = new ThreadLocal<>();
private static String suiteName = "";
@BeforeMethod
public void loggerDoTheThings(ITestContext context, Method method) {
if(suiteName.isEmpty()) {
String suite = context.getSuite().getName() + "(";
String suiteTime = new ConcurrentDateFormatAccess().getCurrentDateSPrecision();
suite += suiteTime + ")";
suiteName = suite;
}
// Test filename = testClass.testMethodname
String classname = this.getClass().getName();
classname = classname.substring(classname.lastIndexOf(".") + 1); //get rid of package info we don't care about
String testName = classname + "." + method.getName();
// Using this to store logger instance for later
String testStart = new ConcurrentDateFormatAccess().getCurrentDateMSPrecision();
methodLogName.set(testName + testStart);
ThreadContext.put("suiteTimestamp", suiteName);
ThreadContext.put("testName", testName);
ThreadContext.put("testStartTime", testStart);
}
@AfterMethod
public void closeTheThings() {
methodLogName.set(null);
}
@AfterSuite
public void closeSuite() {
suiteName = null;
}
@Test
public void testLog1() {
logThings();
}
@Test
public void testLog2() {
logThings();
}
public void logThings() {
logger.info("info message");
logger.debug("debug message");
logger.warn("warn message");
}
}
Log4j 2 似乎被泵入类固醇,如果您已经使用滚动文件追加器免费获得 MDC 日志记录。
无论如何,您的log4j片段看起来很奇怪。我们看到结束追加元素标签,但没有看到其相应的开始追加器标签。
滚动文件追加器名称似乎在动态测试名称和测试开始时间之间有一个空格。
fileName="target/logs/${ctx:suiteTimestamp}/${ctx:testName (${ctx:testStartTime}).log"
建议:你分征服怎么样。
如果确实支持这种类型的动态配置。为什么不尝试先使用动态模式仅配置文件名?
您似乎在获得最简单的配置来解决您的问题之前将 log4j 配置放在完整的类固醇上.
因此,请休息一下,专注于获得: fileName="target/logs/dummyTest_dynamicComponent_${ctx:testName}.log"
为您工作。
在log4j 1.x版本中,您将拥有log4j.debug系统属性来帮助您找出错误的配置,并且输出非常有用。
最后,在 log4j 1.X 版本上,您想要使用的功能需要您显式编程自己的 MDC 追加器。您的 MDC 追加器通常会实例化滚动文件追加器以登录到文件,并且您将利用用户放置的 MDC 上下文 (keyxValue) 对。
但是您正在做的事情看起来很有希望,如果它不适合您,只需降低配置的复杂性。
最后,如果您在遇到以下错误时看到任何日志文件被创建,我会感到非常惊讶:
错误 无法在类类中调用工厂方法 org.apache.logging.log4j.core.appender.RollingFileAppender for element 滚动文件。无法创建滚动文件类型的追加程序。
Log4j 告诉你:嘿,你正在定义的那个附加器。我的工厂试图记录此配置无法处理它,我不会使用此配置实例化滚动文件追加器。
因此,您必须修复该配置。
添加到答案。
在这里,您有一个有效的 Log4j 2 配置,用于执行您想要的操作:
第一个片段是 log4j 2 配置,您将看到根记录器被赋予 3 个不同的附加器来玩。您主要关心追加程序 3,但其他两个追加器更像是您的典型起点。
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<!-- APPENDER 1: CONSOLE -->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<!-- APPENDER 2: ROLLING FILE -->
<RollingFile name="AppenderTwo" fileName="target/logs/test.log" filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
</RollingFile>
<!-- APPENDER 3: ROUTING APPENDER -->
<Routing name="AppenderThree">
<Routes pattern="${ctx:stackOverFlow}">
<!-- Route Nr.1 -->
<Route>
<!-- Rolling file appender for route Nr.1 -->
<RollingFile name="NestedAppender-${ctx:stackOverFlow}" fileName="target/logs/test_threadContext_${ctx:stackOverFlow}.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
</RollingFile>
</Route>
<!-- Route Nr.2 fallback -->
<!-- By having this set to ${ctx:filename} it will match when filename is not set in the context -->
<Route ref="Console" key="${ctx:stackOverFlow}" />
</Routes>
</Routing>
</Appenders>
<Loggers>
<Root level="all">
<AppenderRef ref="Console" />
<AppenderRef ref="AppenderTwo" />
<AppenderRef ref="AppenderThree" />
</Root>
</Loggers>
</Configuration>
最后一个追加程序基于以下线程进行配置:https://issues.apache.org/jira/browse/LOG4J2-129
第二个片段是一个虚拟的 junit 测试,当你从基本原型创建一个新的 maven 项目时,你会从 eclipse 中得到它。您将在测试代码段中看到,流上下文上下文上的堆栈正在设置为线程上下文,就像您在代码段中所做的那样。
package stackoverflow.test.tutorial;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest extends TestCase {
private static final Logger LOGGER = LoggerFactory.getLogger(TestCase.class);
/**
* Create the test case
*
* @param testName
* name of the test case
*/
public AppTest(String testName) {
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(AppTest.class);
}
/**
* Rigourous Test :-)
*/
public void testApp() {
ThreadContext.put("stackOverFlow", "dummyContextValue");
LOGGER.info("LALAL LLA");
assertTrue(true);
}
}
最后一个片段是 maven 依赖项:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>stackoverflow.test</groupId>
<artifactId>tutorial</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>tutorial</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
我觉得 log4j 引入这个新的路由追加器很有趣。如果您可以想象有多少人必须通过MDC上下文支持实现自己的滚动文件追加器才能执行此类操作。它在网络应用程序中非常有用。
干杯。