Shane
Shane

Reputation: 758

How to write only application logs to an external file in android

I am trying to write the logs of my application to an external file. My logs are like Log.e("Offset",""+mOffset); I am using the following code :

public String writeLogToFile()
{
    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);
                }
            bufferedReader.close();
            return log.toString();
        } 
    catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
}

It prints all the logs with system level also. Yes I am putting -d so it is printing but if I put -e or -i it does not write the the file. I just want to write the Log.e("Offset",""+mOffset). Where am I doing wrong?

Upvotes: 4

Views: 999

Answers (1)

J-rooft
J-rooft

Reputation: 1403

Here is how one can read the logs of the current application. To filter logs I obtain process ID (pid) and compare it with every line of logcat output.

In arguments to logcat I specified to read the last 200 lines and display logs with time.

public String writeLogToFile() {
    StringBuilder logs = new StringBuilder();
    int pid = android.os.Process.myPid();
    String pidPattern = String.format("%d):", pid);
    try {
        Process process = new ProcessBuilder()
                .command("logcat", "-t", "200", "-v", "time")
                .redirectErrorStream(true)
                .start();

        InputStream in = null;

        try {
            in = process.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(pidPattern)) {
                    logs.append(line).append("\n");
                }
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    Log.e(TAG, "Cannot close input stream", e);
                }
            }
        }
    } catch (IOException e) {
        Log.e(TAG, "Cannot read logs", e);
    }

    return log.toString();
}

Upvotes: 1

Related Questions