2011-05-30 47 views
65

我想在用戶想要收集日誌時將Android logcat轉儲到文件中。通過adb工具,我們可以使用adb logcat -f filename將日誌重定向到文件,但是如何以編程方式執行此操作?將android logcat數據寫入文件

+0

http://stackoverflow.com/a/8417757/1012284 – 2012-07-03 09:22:13

回答

118

這是讀取日誌的example

您可以將其更改爲寫入文件而不是寫入TextView

需要得到許可在AndroidManifest

<uses-permission android:name="android.permission.READ_LOGS" /> 

代碼:

public class LogTest extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    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); 
     } 
     TextView tv = (TextView) findViewById(R.id.textView1); 
     tv.setText(log.toString()); 
    } catch (IOException e) { 
    } 
    } 
} 
+2

@ jkhouw1 ... +60最佳答案我見過和發佈答案,(也是好方法我向你學習)這個答案將永遠是有益的,即使鏈接死了,我只需要添加滾動視圖,我做了我想要的,因爲你的回答,乾杯! – swiftBoy 2012-07-03 05:58:05

+0

很好..但有沒有辦法根據標籤過濾這些日誌? – AbhishekB 2012-08-28 10:55:55

+1

我還沒有測試過這個,但我認爲你會改變它爲「logcat -d -s YourTagToFilterOn」 – jkhouw1 2012-08-28 11:28:13

38

logcat的可以直接寫入文件:

public static void saveLogcatToFile(Context context) {  
    String fileName = "logcat_"+System.currentTimeMillis()+".txt"; 
    File outputFile = new File(context.getExternalCacheDir(),fileName); 
    @SuppressWarnings("unused") 
    Process process = Runtime.getRuntime().exec("logcat -f "+outputFile.getAbsolutePath()); 
} 
上的logcat

更多的信息:看到http://developer.android.com/tools/debugging/debugging-log.html

+1

由於logcat -f不會自動退出,因此該命令似乎失速。以任何方式將日誌寫入文件並自動退出類似於logcat -d的進程? – Phillip 2014-01-08 06:39:27

+0

嘗試把&放到最後使其成爲背景。 – ShihabSoft 2015-06-01 10:49:40

+4

logcat -df 將所有日誌匯入並立即退出。 – 2016-02-26 10:24:50

1

或者你可以試試這個瓦里安

 
try { 
    final File path = new File(
      Environment.getExternalStorageDirectory(), "DBO_logs5"); 
    if (!path.exists()) { 
     path.mkdir(); 
    } 
    Runtime.getRuntime().exec(
      "logcat -d -f " + path + File.separator 
        + "dbo_logcat" 
        + ".txt"); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
0
public static void writeLogToFile(Context context) {  
    String fileName = "logcat.txt"; 
    File file= new File(context.getExternalCacheDir(),fileName); 
    if(!file.exists()) 
     file.createNewFile(); 
    String command = "logcat -f "+file.getAbsolutePath(); 
    Runtime.getRuntime().exec(command); 
} 

以上方法將所有日誌寫入到文件中。也請在下面添加權限清單文件

<uses-permission android:name="android.permission.READ_LOGS" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />