3

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?

Nestor
  • 8,194
  • 7
  • 77
  • 156
  • 1
    please take a look at my previous post: http://stackoverflow.com/questions/19897628/need-to-handle-uncaught-exception-and-send-log-file – Peri Hartman Dec 10 '13 at 14:58
  • Your answer seems promising, especially *extractLogToFile*. However, when I use on a 2.3 phone with the following line: "logcat -d -v MyTAG:v *:S"*, I always get a -1 in *reader.read()*. What should I set? – Nestor Dec 21 '13 at 11:34
  • That probably means your filtering on logcat is excluding all rows. Try removing the filtering and see if you get something. – Peri Hartman Dec 21 '13 at 15:42
  • I didn't have the required permission. After I added it, it worked well. – Nestor Dec 23 '13 at 10:23

2 Answers2

7

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;
    }
}
Kuffs
  • 35,581
  • 10
  • 79
  • 92
  • A very important thing: reading the log requires a permission! Use this in your manifest: **** – Nestor Dec 23 '13 at 10:22
  • 2
    You do not need this permission to collect your own apps logs in Api 16 up. See this post by hackbod (android software engineer). https://groups.google.com/d/msg/android-developers/6U4A5irWang/AvZsrTdfICIJ – Kuffs Dec 23 '13 at 10:39
  • Thanks for the information. I use my log collector starting from API level 10. – Nestor Dec 23 '13 at 10:50
4

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

Community
  • 1
  • 1
David S.
  • 6,567
  • 1
  • 25
  • 45