如何在安卓系统中将应用程序日志仅写入外部文件

4
我正在尝试将应用程序的日志写入外部文件。我的日志像这样Log.e("Offset",""+mOffset);我使用以下代码:
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;
        }
}

它打印系统级别的所有日志。是的,我加了-d参数所以它在打印,但如果我加上-e或-i,则不会写入文件。我只想写入Log.e("Offset",""+mOffset)。我错在哪里了?


你尝试过这个 Log.VERBOSE 吗? - Rahul Baradia
应该像这样 Runtime.getRuntime().exec("logcat Log.VERBOSE"); 如果是这样,那么我的日志必须在哪个级别? - Shane
Runtime.getRuntime().exec("logcat -v time"); 可能会像这样,或者 Runtime.getRuntime().exec("logcat -v"); - Rahul Baradia
尝试使用此链接代码 https://github.com/androidnerds/logger/blob/master/src/com/michaelrnovak/util/logger/service/LogProcessor.java,可能会对您有所帮助。再试一次并使用大写字母“V”,即Runtime.getRuntime().exec("logcat -V"); - Rahul Baradia
我应该放置Log.v("msg","msg") 还是 Log.e("msg","msg"),两者都可以。 - Shane
显示剩余2条评论
1个回答

1

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接