Android日志记录:从应用程序本身进行过滤

问题描述 投票:2回答:1

是否可以通过编程方式配置Android应用程序以过滤发送到logcat的日志消息?我确实知道,可以将logcat配置为过滤掉内容,但是我想在Android应用程序中执行相同的操作。

用例-我实际上是在测试用例中使用robolectric,这样我可以直接在主机上运行,​​而不能在模拟器上运行。对于非GUI的东西,这实际上非常方便。我的一些代码会发出Android日志。我无法附加logcat来查看其输出。我可以将日志重定向到常规标准输出。但目前我还没有过滤功能,因此它要么是grep,要么是相似的,或者是通过数千行无关的内容进行筛分。

android testing junit robolectric
1个回答
0
投票

这就是我所做的:

    public class CustomPrintStream extends PrintStream {

    private String regexFilter;
private Pattern pattern;

public IonPrintStream(@NonNull File file) throws FileNotFoundException {
    super(file);
}

public String getRegexFilter() {
    return regexFilter;
}

public void setRegexFilter(String regexFilter) {
    this.regexFilter = regexFilter;
    if (regexFilter != null && !regexFilter.isEmpty()) {
        pattern = Pattern.compile(regexFilter);
    } else {
        pattern = null;
    }
}

@Override
public void println(String x) {

    if (x != null && pattern != null && !pattern.matcher(x).find()) {
        return;
    }

    System.out.println(x);
}
}

在Robolectric上的用法(您可以在@Before方法上进行此操作:]

        File file = new File("log.txt");
        if (!file.exists() && !file.createNewFile()) {
            throw new RuntimeException("Log file could not be created");
        }

        CustomPrintStream printStream = new CustomPrintStream(file);
        printStream.setRegexFilter("[your regex here]");
        ShadowLog.stream = printStream;
© www.soinside.com 2019 - 2024. All rights reserved.