繁体   English   中英

我如何将所有logcat条目存储到android中的文件

[英]How can i get all logcat entries stored to a file in android

当我在PC上使用命令提示符并连接设备并运行Abd执行以下命令时

abd logcat -d > abc.txt

它会返回一个大文件“ abc.txt”,其中包含所有应用程序的logcat的所有条目。 但是,当我在Android上的应用程序中运行相同的命令以通过制作文件将其存储在SD卡上时,它仅存储最近的logcat条目,并且仅存储此应用程序的日志,甚至不包含以前的日志。 有人可以告诉我为什么会这样吗?我也已授予READ_LOGS权限

这是Android代码

 String fullName = "appLog.txt";
    File file = new File (Environment.getExternalStorageDirectory(), fullName);

    //clears a file
    if(file.exists()){
        file.delete();
    }


    //write log to file
    try {
        String command = String.format("logcat -d");        
        Process process = Runtime.getRuntime().exec(command);

        BufferedReader reader = new BufferedReader(new   InputStreamReader(process.getInputStream()));
        StringBuilder result = new StringBuilder();
        String currentLine = null;

        while ((currentLine = reader.readLine()) != null) {

                   result.append(currentLine);
                   result.append("\n");

        }

        FileWriter out = new FileWriter(file);
        out.write(result.toString());
        out.close();


    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
    }


    //clear the log
    try {
        Runtime.getRuntime().exec("logcat -c");
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
    }

在Jelly Bean中,这种情况已更改。 应用程序只能读取自己的日志,并且不再需要READ_LOGS权限。

或者,您可以将log4j用于android 您可以使用文件追加器将所有日志存储在某个文件中,还可以使用LogCatAppender将日志打印到logcat,因此您可以在eclipse中进行开发时观看日志,例如

为了捕获所有未捕获的异常,您可以创建实现UncaughtExceptionHandler的类,然后将其与Thread.setDefaultUncaughtExceptionHandler()一起使用。 这对于将崩溃报告(堆栈跟踪)打印到日志和/或单独的文件很有用。

public void appendLog(String text)
    {       
       File logFile = new File("/sdcard/log.txt");
       if (!logFile.exists())
       {
          try
          {
             logFile.createNewFile();
          } 
          catch (IOException e)
          {
             // TODO Auto-generated catch block
             e.printStackTrace();
          }
       }
       try
       {
          BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
          buf.append(text);
          buf.newLine();
          buf.close();
       }
       catch (IOException e)
       {
          // TODO Auto-generated catch block
          e.printStackTrace();
       }
}

并使用该方法从所需的任何位置进行日志记录。

appendLog("your message" + anyvalueyouwanttolog );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM