How to Remove Debug Logging with ProGuard?

ProGuard is a tool that helps you to optimize and obfuscate your Java or Kotlin applications and libraries.

One of the questions users frequently ask is how to use ProGuard to remove logging code. For the application developer, removing logging is normally considered a security function rather than an optimization. The purpose is usually to make sure that any debug logging information does not leak to the outside world. However to remove logging we will use ProGuard’s optimization capabilities as opposed to obfuscation.

In the ProGuard manual you will find that you can use the -assumenosideeffects option to remove logging.

Why does this work?

When you invoke a method in your code, you generally do it with one (or both) of the following purposes:

  • Either you expect the method to return a value that you will use in your business logic (returning a value is the main effect);
  • Or you expect the method to have an effect on its own, for example output something on screen, or send a message over the network (this is a side effect).

Contrary to what your intuition might suggest, side effects are usually not hidden or undesirable, it’s just terminology in software development that means that a method affects the outside world in a way that goes beyond returning a value.

Your logging methods have a side effect - to output a log. So why do you then need to tell ProGuard to assume they do not have a side effect? The reason is that ProGuard will assume a method is used if it has a main effect or a side effect. If a method does not have either effect, or its return value is never used, then the whole method is considered unused, and therefore can be removed during optimization. This will of course only work if optimization is turned on in your ProGuard configuration.

How to use it practically?

Check out this example in ProGuard manual.

  1. Make sure that optimization is turned on (for example by using the proguard-android-optimize.txt default configuration)
proguard {
    configurations {
        release {
            defaultConfiguration 'proguard-android-optimize.txt'
            configuration 'proguard-project.txt' 
        }
    }
}
  1. Use the -assumenosideeffects option to mark logging methods. Be sure not to use a * wildcard to not break your code.

For Android logging you can use this snippet:

-assumenosideeffects class android.util.Log {
    public static boolean isLoggable(java.lang.String, int);
    public static int v(...);
    public static int i(...);
    public static int w(...);
    public static int d(...);
    public static int e(...);
}