Adibe7
Adibe7

Reputation: 3539

Logcat is redirected to file more then once

I've redirected the logcat to file in my code when my app starts. But when my application is restarted, the redirecting code runs again and the result is that each line in the log is written twice.

How can I execute the command and make sure the child process dies when the parent dies?

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

How can i make sure that my app's logcat is redirected only once? (Whats happends if other app calls the logcat and redirects it to it's own file, will the check still work then?)

thanks!

Upvotes: 0

Views: 606

Answers (3)

Adibe7
Adibe7

Reputation: 3539

/** 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;
    }
}

Upvotes: -1

bbaja42
bbaja42

Reputation: 2169

Two options:
a) Make a static global variable that will contain information weather Logcat was already redirected or not.
b) Make a file on the sdcard or in the app directory (xml or properties file) containing info weather LogCat was already redirected.

Upvotes: 1

Lukas Knuth
Lukas Knuth

Reputation: 25755

If you only use LogCat for debugging purposes, you might want to read this.

After you Activated LogCat, you can open the LogCat-View in Eclipse which will then show you all the LogCat-Output, so you don't need to write it to a file in the first place.

Upvotes: 1

Related Questions