【发布时间】:2011-09-04 17:21:58
【问题描述】:
每当用户想要收集日志时,我想将 Android logcat 转储到一个文件中。通过 adb 工具,我们可以将日志重定向到使用 adb logcat -f filename 的文件,但我如何以编程方式做到这一点?
【问题讨论】:
每当用户想要收集日志时,我想将 Android logcat 转储到一个文件中。通过 adb 工具,我们可以将日志重定向到使用 adb logcat -f filename 的文件,但我如何以编程方式做到这一点?
【问题讨论】:
这是阅读日志的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) {
}
}
}
【讨论】:
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
【讨论】:
或者你可以试试这个变体
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();
}
【讨论】:
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);
}
上述方法会将所有日志写入文件。另外请在 Manifest 文件中添加以下权限
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
【讨论】: