0

当我的应用程序启动时,我已将 logcat 重定向到我的代码中的文件。但是当我的应用程序重新启动时,重定向代码再次运行,结果是日志中的每一行都被写入了两次。

如何执行命令并确保子进程在父进程死亡时死亡?

String.format("logcat -f %s -r %d", filename.getAbsolutePath(), LOG_FILE_SIZE_KB);    
Runtime.getRuntime().exec(cmd);

如何确保我的应用程序的 logcat 只重定向一次?(如果其他应用程序调用 logcat 并将其重定向到它自己的文件会发生什么,那么检查仍然有效吗?)

谢谢!

4

3 回答 3

1

如果您仅将 LogCat 用于调试目的,您可能需要阅读.

激活 LogCat 后,您可以在 Eclipse 中打开 LogCat-View,然后它将显示所有 LogCat-Output,因此您无需将其写入文件。

于 2011-06-19T12:16:54.127 回答
1

两个选项:
a) 制作一个静态全局变量,其中包含天气 Logcat 是否已被重定向的信息。
b) 在 sdcard 或 app 目录(xml 或属性文件)中创建一个文件,其中包含天气 LogCat 已被重定向的信息。

于 2011-06-19T12:50:44.557 回答
-1
/** Redirects the log output to the SDCard.
 *  
 * make sure your app has the WRITE_EXTERNAL_STORAGE and READ_LOGS permissions - 
 *  or it won't allow it to read logs and write them to the sdcard.
 *  If the application doesn't have the permissions, there will be no exception
 *  and the program will continue regularly.
 */
public static void redirectOutputToFile()
{
    s_enableLogs = true;

    if (s_logcatProcess != null)
    {
        Logger log = new Logger("Logger");  

        log.info("redirectOutputToFile() called more then once, perhaps from service onCreate and onStart.");

        return;
    }

    try 
    {
        String path = Environment.getExternalStorageDirectory() + LOG_FILE_NAME;
        File filename = new File(path);

        filename.createNewFile();

        //http://www.linuxtopia.org/online_books/android/devguide/guide/developing/tools/android_adb_logcatoptions.html
        String cmd = String.format("logcat -v time -f %s -r %d -n %d", filename.getAbsolutePath(), LOG_FILE_SIZE_KB, LOG_FILE_ROTATIONS);    

        s_logcatProcess = Runtime.getRuntime().exec(cmd);
    } 
    catch (IOException e) 
    {       
        Logger log = new Logger("Logger");
        log.exception(e);
    }
}

/** Kills the logcat process that was created in the redirectOutputToFile() method. */
public static void killLogcatProcess()
{
    // first update the log mode state
    s_enableLogs = false;

    if (s_logcatProcess != null)
    {
        s_logcatProcess.destroy();
        s_logcatProcess = null;
    }
}
于 2011-07-20T11:49:19.450 回答