我正在尝试在 allure 报告中显示 logj4 日志,有不同的方法可以做到这一点,我想找到最好的解决方案。
作为一个选项,我可以创建这样的东西:
public class AllureLogger {
private static final Logger logger = LogManager.getLogger(AllureLogger.class);
public static void info(String message) {
logger.info(message);
attachLogToAllure("INFO: " + message);
}
public static void error(String message) {
logger.error(message);
attachLogToAllure("ERROR: " + message);
}
@Attachment(value = "{logMessage}", type = "text/plain")
private static String attachLogToAllure(String logMessage) {
return logMessage;
}
}
但也许有更合适的方法来做到这一点。我没有找到任何用于 log4j - allure 集成的库。
您可以使用AllureLifecycle修改您当前的测试用例/测试步骤。另外,您可以在测试失败后使用侦听器修改吸引力(例如 TestNG 侦听器)。
@Log4j2
public class TestListener extends AllureTestNg {
@Override
public void onTestStart(ITestResult testResult) {
log.debug("Running test method: {}",testResult.getMethod().getMethodName());
}
}
另外,你不需要创建logger实例,而是可以在类上方使用注解@Log4j或@Log4j2(但要注意包)。
您可以将 log4j 配置为每个测试都记录到单独的文件,然后将整个文件附加到报告中。
逐步设置:
Routing:
- name: Test
Routes:
pattern: '$${ctx:uuid}'
Route:
RollingFile:
immediateFlush: true
append: false
name: 'RollingFile-${ctx:uuid}'
fileName: '${logDir}/test-${ctx:uuid}.log'
filePattern: '${logDir}/%d{yyyy-MM-dd}/archived_%d{HH-mm}-${ctx:uuid}.log'
PatternLayout:
pattern: '%d{HH:mm:ss:SSS} [%t] %-5level %logger{36} - %msg%n'
Policies:
- OnStartupTriggeringPolicy
public class AllureTestListener implements TestLifecycleListener {
protected static final String LOG_PATH = "build/logs/";
private static final ThreadLocal<String> TL_TEST_UUID = new ThreadLocal<>();
private static final String LOG_FILE_PATTERN = "test-%s.log";
private final Logger LOGGER = LogManager.getLogger();
@Override
public void afterTestStart(TestResult result) {
startTestLogging();
}
@Override
public void beforeTestStop(TestResult result) {
stopTestLogging();
}
private void startTestLogging() {
TL_TEST_UUID.set(UUID.randomUUID().toString());
ThreadContext.put("uuid", TL_TEST_UUID.get());
}
private void stopTestLogging() {
ThreadContext.remove("uuid");
String logFileName = String.format(LOG_FILE_PATTERN, TL_TEST_UUID.get());
File logFile = Paths.get(LOG_PATH, logFileName).toFile();
addLogAttachment(logFile);
}
private void addLogAttachment(File logFile) {
try {
Allure.addAttachment("Log", new FileInputStream(
logFile));
} catch (FileNotFoundException e) {
LOGGER.warn(String.format("There is no log file %s", logFile.getName()));
}
}
}
在 log4j2 配置中,我们有一个路由附加程序,它根据 uuid 上下文属性将日志记录到单独的文件。 AllureTestListener 通过将测试 uuid 放入
afterTestStart
方法中的 TL_TEST_UUID 线程局部变量中来控制每个线程的 uuid(以支持并行测试运行)。然后,在测试停止之前,我们删除该变量,并将日志文件附加到报告中。