Nestor
Nestor

Reputation: 8384

How to collect LogCat messages in an Android application

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?

Upvotes: 3

Views: 2715

Answers (2)

Kuffs
Kuffs

Reputation: 35661

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;
    }
}

Upvotes: 8

David S.
David S.

Reputation: 6705

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

Upvotes: 4

Related Questions