有没有一种方法可以将logcat的输出重定向到InputStream或类似的东西? 我想到了类似于在C中如何重定向stderr的内容。
我想在我的应用程序启动时重定向它,以便发生的所有事情都被转储到文件中。
$ adb logcat > textfile.txt
System.setErr
。它可以轻松地将错误输出重定向到文件中。System.setErr(new PrintStream(new File("<file_path>"))
System.err
的输出(如果以相同方式重定向,则可能还包括 System.out
)。但是,输出将不包括 Android 在每行前缀中添加的内容(时间戳、PID、TID 等),并且通过 Log
类记录的任何内容也不会在此处重定向。 - user149408如果想要仅过滤您的应用程序的logcat,请尝试以下方法:
int pid = android.os.Process.myPid();
File outputFile = new File(Environment.getExternalStorageDirectory() + "/logcat.txt");
Log.d("zzz","outputFile: " + outputFile);
try {
String command = "logcat | grep " + pid + " > " + outputFile.getAbsolutePath();
Log.d("zzz","command: " + command);
Process p = Runtime.getRuntime().exec("su");
OutputStream os = p.getOutputStream();
os.write((command + "\n").getBytes("ASCII"));
} catch (IOException e) {
}
su
并且不授予应用程序READ_LOGS
权限的情况下运行logcat
,这将限制返回给调用方UID(即您的应用程序,包括早期实例和子进程)的条目。但这似乎因Android发行版而异。否则,logcat
还具有-e
选项,可以按正则表达式进行过滤。 - user149408 located in utilities...
val publicDirectory = globalContext.getExternalFilesDir(null)
publicDirectoryName = publicDirectory?.toString() + "/"
fun redirectLogcatToFile() {
try {
val filename =
File(Utilities.publicDirectoryName + "logcat.txt")
filename.createNewFile()
val cmd = "logcat -v time -f " + filename.getAbsolutePath() +" -s " + logcatTag
Runtime.getRuntime().exec(cmd)
} catch (ex: Exception ) {
Utilities.toastOnAnyThread("Utilities.redirectLogcatToFile: " + ex.message)
}
}
fun Log( message : String ){
Log.i(logcatTag, message )
}