【发布时间】:2011-03-22 13:00:37
【问题描述】:
我正在尝试将我的应用程序的日志重定向到 sdcard 文件。但我没有这样做。我正在尝试这样的事情。
String cmd= "logcat -v time ActivityManager:W myapp:D *:* >\""+file.getAbsolutePath()+"\"";
Runtime.getRuntime().exec(cmd);
我也尝试了 -f 选项,但它也不起作用。
【问题讨论】:
我正在尝试将我的应用程序的日志重定向到 sdcard 文件。但我没有这样做。我正在尝试这样的事情。
String cmd= "logcat -v time ActivityManager:W myapp:D *:* >\""+file.getAbsolutePath()+"\"";
Runtime.getRuntime().exec(cmd);
我也尝试了 -f 选项,但它也不起作用。
【问题讨论】:
这是我的工作版本:
try {
File filename = new File(Environment.getExternalStorageDirectory()+"/logfile.log");
filename.createNewFile();
String cmd = "logcat -d -f "+filename.getAbsolutePath();
Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
找到您的日志文件 /sdcard/logfile.log
【讨论】:
-d 导致仅写入当前缓冲区。 Logcat 然后停止写入任何其他数据。查看熊的答案以获得连续写作。
使用logcat -f <filename> 将其转储到文件系统中的文件中。
确保您使用的文件名在 SD 卡中,即以 /sdcard/... 开头。
另外,为了向logcat 程序传递参数,您应该向exec 方法传递一个字符串数组(而不是一个字符串):
String[] cmd = new String[] { "logcat", "-f", "/sdcard/myfilename", "-v", "time", "ActivityManager:W", "myapp:D" };
最后,如果所有其他方法都失败了,请使用 logcat 的完整路径:/system/bin/logcat 而不仅仅是 logcat。
【讨论】:
READ_LOGS。
/**
* Launches a logcat process.
* To stop the logcat preserve the use:
* process.destroy();
* in the onBackPressed()
*
* @param filename destination of logcat output
* @return Process logcaat is running on
*/
public Process launchLogcat(String filename) {
Process process = null;
String cmd = "logcat -f " + filename + "\n";
try {
process = Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
process = null;
}
return process;
}
【讨论】:
尝试在字符串中的每个元素后使用空格。否则,它将被视为没有空格的单行命令并且什么都不做。
【讨论】:
如果您得到一个空日志文件,请尝试将文件扩展名从 .log 更改为 .txt。
【讨论】:
public static void saveLogInSDCard(Context context){
String filename = Environment.getExternalStorageDirectory() + File.separator + "project_app.log";
String command = "logcat -d *:V";
try{
Process process = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try{
File file = new File(filename);
file.createNewFile();
FileWriter writer = new FileWriter(file);
while((line = in.readLine()) != null){
writer.write(line + "\n");
}
writer.flush();
writer.close();
}
catch(IOException e){
e.printStackTrace();
}
}
catch(IOException e){
e.printStackTrace();
}
}
【讨论】: