Stripping Log Statements using Proguard
This post describes how to use Proguard to strip log statements from your Android app; good for both the standard android.util.Log
class as well as when using Timber.
Logging only on DEBUG Builds
Sometimes you want to remove all log statements from your app and it is as simple as not logging in your production releases.
You can wrap your calls to Log
inside a check to ensure you are on a debug build.
if(BuildConfig.DEBUG) Log.i(TAG, "foo");
In Timber
land, you’d only plant a DebugTree
and not bother about planting anything else.
if(BuildConfig.DEBUG) Timber.plant(new Timber.DebugTree());
Logging in Production Too
However, if you need to sometimes log, it gets more complicated. Let’s say you use Timber
and plant a debug tree which will handle your logging while in development, but you also want a logger which will log any messages which are a warning
or greater when in production too.
Logging in Production? 😱
You probably shouldn’t actually log in production. So maybe you don’t actually log to logcat
and instead send the most important logs to your crash reporting tool.
Stripping Log Statements
In debug
there is nothing to do; you want to see all logs statements. But in production, you want strip all logs except for warn
and error
. Proguard can help us here.
In build.gradle
you can enable Proguard
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
Note, that’s proguard-android-optimize.txt ☝️
Stripping Standard Log
Statements
Modify the proguard-rules.pro
file, which should live under your standard Android app
directory:
Stripping Timber Log Statements
Modify the proguard-rules.pro
file:
Testing it Works
Add the following to a class you know will be executed (delete as appropriate depending on if you’re stripping standard Log
statements or Timber
logs)
When you run in debug
mode, you should see all of the statements in logcat
.
When running the app after proguarding, however, you should only see the output from warning
and error
log statements.
Bonus: Using Proguard Only to Remove Logging
If you don’t really want to use Proguard
, but do quite like the idea of it stripping out your logs for you, you can disable all proguarding except for the log stripping.
Add the following to your proguard-rules.pro
to achieve this:
-dontwarn **
-target 1.7
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose-optimizations !code/simplification/arithmetic,!code/allocation/variable
-keep class **
-keepclassmembers class *{*;}
-keepattributes *
Attributions
Cover photo by Malte Wingen on Unsplash
StackOverflow — https://stackoverflow.com/a/15593061/1654145