(日志)使用柑橘框架查看文件

(log) File watching with citrus-framework

有没有办法and/or从被测系统观察日志文件的最佳做法是什么? 我的要求是根据 SUT 生成的已知模式验证 presence/absence 日志条目。

非常感谢!

嗯,我认为没有专门为此设计的 Citrus 工具。但我认为这是一个非常好的主意。您可以 open an issue 并请求此功能。

同时,这是我们在我们的一个项目中使用的解决方案,用于检查应用程序日志是否包含我们测试生成的特定字符串。

sleep(2000),
echo("Searching the log..."),
new AbstractTestAction() {
    @Override
    public void doExecute(TestContext context) {
        try {
            String logfile = FileUtils.getFileContentAsString(Paths.get("target", "my-super-service.log").toAbsolutePath().normalize());
            if (!logfile.contains("ExpectedException: ... | Details: BOOM!.")) {
                throw new RuntimeException("Missing exceptions in log");
            }
        } catch (IOException e) {
            throw new RuntimeException("Unable to get log");
        }
    }
}

你可以用更优雅的解决方案替换那个简单的包含:

String grepResult = grepForLine(LOGFILE_PATH, ".*: SupermanMissingException.*");
if (grepResult == null) {
    throw new RuntimeException("Expected error log entry not found");
}

该函数遍历每一行,搜索与提供的正则表达式的匹配项。

public String grepForLine(Path path, String regex) {
        Pattern regexp = Pattern.compile(regex);
        Matcher matcher = regexp.matcher("");

        String msg = null;

        try (
                BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset());
                LineNumberReader lineReader = new LineNumberReader(reader)
        ) {
            String line;
            while ((line = lineReader.readLine()) != null) {
                matcher.reset(line); //reset the input
                if (matcher.find()) {
                    msg = "Line " + lineReader.getLineNumber() + " contains the error log: " + line;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return msg;
}