Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficient way to put debug/log statements in code - so they do not influence runtime

In C-derivative languages there is the possibility to have conditional code for debug and runtime. That way there is no overhead left in the runtime.

How would I do this with Java/Android and the Log.i statements? If I just use a constant global boolean debugOn that obviously leaves the redundant checks in the runtime.

What is the best approach for conditional Log-statements?

Many thanks

EDIT:

Since there are quite some comments following the accepted answer I post my conclusion here....

private static final boolean DEBUG = true;

if (DEBUG) Log.i("xxx",this.getClass().getName()+ "->" + Thread.currentThread().getStackTrace()[2].getMethodName() );

...just like in xCode :)

like image 918
user387184 Avatar asked Nov 08 '11 13:11

user387184


People also ask

Is trace higher than debug?

The TRACE log level captures all the details about the behavior of the application. It is mostly diagnostic and is more granular and finer than DEBUG log level. This log level is used in situations where you need to see what happened in your application or what happened in the third-party libraries used.


1 Answers

Android build system started providing a constant BuildConfig.DEBUG some time ago, so I suggest using it and writing the code like this:

if (BuildConfig.DEBUG) Log.i(TAG, "Message");

No redundant checks will be made since it's a constant. This code will be optimized even by compiler, but you also have ProGuard at your disposal. Even if the checks are in place, any possible impact on performance should be negligible.

This approach used to have one drawback that you had to edit this constant yourself, either manually or through a custom rule in the build file. Now, however, this is handled automatically by the build system, so you don't have to do anything yourself.

like image 59
Malcolm Avatar answered Nov 07 '22 11:11

Malcolm