Bug or feature in android.util.Log? - Log.isLoggab

2019-06-21 02:54发布

Update: Reformulated the question and header:

I always thought that expensive android Logging methods can be optimized by asking if logging is active like this

    import android.util.Log;

    if (Log.isLoggable("MyContext", Log.DEBUG))
    {
        Log.d("MyContext", "my logging: " + callExpensiveCalculation());
    }

However when trying this with the android 2.2 emulator my Log.d() is never called.

So i tried this code

    Log.v(MY_CONTEXT, "VERBOSE logging is active: " + Log.isLoggable(MY_CONTEXT, Log.VERBOSE));
    Log.d(MY_CONTEXT, "DEBUG logging is active: " + Log.isLoggable(MY_CONTEXT, Log.DEBUG));
    Log.i(MY_CONTEXT, "INFO logging is active: " + Log.isLoggable(MY_CONTEXT, Log.INFO));
    Log.w(MY_CONTEXT, "WARN logging is active: " + Log.isLoggable(MY_CONTEXT, Log.WARN));
    Log.e(MY_CONTEXT, "ERROR logging is active: " + Log.isLoggable(MY_CONTEXT, Log.ERROR));

and to my surprise i got

02-27 19:05:43.015: V/MyContext(334): VERBOSE logging is active: false
02-27 19:05:43.015: D/MyContext(334): DEBUG logging is active: false
02-27 19:05:43.015: I/MyContext(334): INFO logging is active: true
02-27 19:05:43.015: W/MyContext(334): WARN logging is active: true
02-27 19:05:43.015: E/MyContext(334): ERROR logging is active: true

so logging works even if logging is disabled. Is this a bug in android or in my test-code?

Is there an other way to find out if debugging (or one of the other loglevels) is active or not?

I use eclipse logcat-view with log-level verbose and started the test from eclipse with run as android-app

1条回答
够拽才男人
2楼-- · 2019-06-21 03:23

isLoggable is really just a mechanism to provide a flag for certain tags for your convenience. It doesn't actually do anything to disable logging. Your first block of code is correct:

if (Log.isLoggable("MyContext", Log.DEBUG))
{
    Log.d("MyContext", "my logging: " + callExpensiveCalculation());
}

This will log or not log depending on if isLoggable returns true or false. However, when you do this (without checking isLoggable):

Log.d(MY_CONTEXT, "DEBUG logging is active: " + Log.isLoggable(MY_CONTEXT, Log.DEBUG));

It will log regardless of what isLoggable would have returned had you called it. In short, you need to do that check everywhere that you log if you want to enable/disable logging based on that flag. The if statement is the part that lets you skip unnecessary logs. If the if clause is false, the code inside is never run.

查看更多
登录 后发表回答