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

vsmadaxz  于 5个月前  发布在  Android
关注(0)|答案(2)|浏览(69)

有没有一种方法可以通过编程方式配置Android应用程序来过滤发送给logcat的日志消息?我确实理解,logcat可以配置为过滤掉东西,但我想在Android应用程序中做同样的事情。

用例-我实际上使用robolectric作为我的测试用例,我可以直接在我的主机上运行,而不是在模拟器上。这实际上对于非GUI的东西非常方便。我的一些代码会发出Android日志。我不能附加logcat来查看其输出。我可以将日志重定向到常规的stdout。但在这一点上我没有过滤,所以它要么是grep或类似的,要么是筛选成千上万行不相关的东西。

yc0p9oo0

yc0p9oo01#

我就是这么做的:

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;


在你的例子中,因为你不想显示一些日志,你可以像这样过滤:

//I don't want to log CursorWindowStats and SQLiteCursor tags:
        printStream.setRegexFilter("^((?!CursorWindowStats|SQLiteCursor).)*$");

hpxqektj

hpxqektj2#

在Kotlin中:

class FilterLogStream(stream: OutputStream, private val pattern: Pattern) : PrintStream(stream) {
    override fun println(x: String) {
        if (!pattern.matcher(x).find()) return
        super.println(x)
    }
}

fun PrintStream.filter(regex: String): PrintStream = FilterLogStream(this, Pattern.compile(regex))

字符串
使用方法:

ShadowLog.stream = System.out.filter("^(?!W/ShadowLegacyPath).*$")

相关问题