Simple way to write android Logs

Everyone writes logs during project development, as logs are really helpful for debugging applications, displaying exceptions or errors. But this can lead to headache if you forgot to remove those logs at the end of project, as many of us don’t want to show our apps api calls and its responses to the world for security reasons. 🙂

So how can we get rid of these logs during release of our app?

Clean way to write solution for above problem will be,

  1. Use BuildConfig.DEBUG variable – which is automatically generated by the android build, by default set to true which means it is in debug mode and false when you export a release build.
  2. Wrap in helper SimpleLog class which will display logs only when we are debugging.

Lets have a look how to use these-

First of all we have to write custom class like below one

[java]
public class SimpleLog{

public static void log(String TAG, String message) {
if (BuildConfig.DEBUG) {
Log.d(TAG, message);
}
}

public static void logError(String TAG, String message) {
if (BuildConfig.DEBUG) {
Log.e(TAG, message);
}
}

public static void logException(String TAG, Exception exe) {
if (BuildConfig.DEBUG) {
Log.e(TAG, exe.getMessage());
exe.printStackTrace();
}
}
}
[/java]

After our class is ready we have to call,

[java]SimpleLog.log(“AppName”,”This is simple way to display logs”);[/java]

instead of

[java]Log.d(“AppName”,”This is simple way to display logs”);[/java]

And for logging error, simply call-

[java]SimpleLog.logError(“AppName”,”Error”);[/java]

and that’s how we simplified a way to write logs. 🙂

Note:

[java]BuildConfig.DEBUG=true[/java]

when apps build variant will be debug.

[java]BuildConfig.DEBUG=false[/java]

when apps build variant will be released, so no logs will be displayed. 🙂