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
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:This will log or not log depending on if
isLoggable
returnstrue
orfalse
. However, when you do this (without checkingisLoggable
):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. Theif
statement is the part that lets you skip unnecessary logs. If theif
clause isfalse
, the code inside is never run.