How to collect LogCat messages in an Android application

谁都会走 提交于 2019-12-12 09:12:42

问题


I have an application and I'd like to collect the LogCat messages of a specified level and tag.

Can I somehow get the accumulated messages at some point? I don't want to collect the messages one by one, it should be the sum of them like when I use adb to read the actual log. Is this possible?


回答1:


Try this: Note that in Android 4 you will only see the log messages that were written by your own app unless you have root access.

public static String getLog(Context c) {
    try {
        Process process = Runtime.getRuntime().exec("logcat -d");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        StringBuilder log = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            log.append(line);
            log.append("\n");
        }

       return log.toString();

    } catch (IOException e) {
       return null;
    }
}



回答2:


Why not just write them to a file instead? LogCat is really for real-time logs. There are lots of good quality logging packages that can log to a file if that's what you want to do.

Just as an example:

How to write logs in text file when using java.util.logging.Logger



来源:https://stackoverflow.com/questions/20497636/how-to-collect-logcat-messages-in-an-android-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!