Filter sensitive json fields in Retrofit 2 logging

748 Views Asked by At

I am using a custom Interceptor for Retrofit2 in order to log all request/response jsons with pretty format.

The problem is this log is not only for local debugging purposes, but also is sent to Instabug (something like Crashlytics) to help debug user reported issues or crashes.

And so it is important for the info in that service to not contain user identifiable information like email, passwords, etc.

Since in the Interceptor we only get the raw request/response is the only solution to manually check for all possible sensitive fields and remove them from the logged version of the json?

1

There are 1 best solutions below

0
Manish Kumar Sharma On

Here is a simple way to filter any request/response params from the logs:

// Request patterns to filter
private static final String[] REQUEST_PATTERNS = {
    "Content-Type",
};
// Response patterns to filter
private static final String[] RESPONSE_PATTERNS = {"Server", "server", "X-Powered-By", "Set-Cookie", "Expires", "Cache-Control", "Pragma", "Content-Length", "access-control-allow-origin"};

// Log requests and response
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
    @Override
    public void log(String message) {

        // Blacklist the elements not required
        for (String pattern: REQUEST_PATTERNS) {
            if (message.startsWith(pattern)) {
                return;
            }
        }
        // Any response patterns as well...
        for (String pattern: RESPONSE_PATTERNS) {
            if (message.startsWith(pattern)) {
                return;
            }
        }
        Log.d("RETROFIT", message);
    }
});
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

Here is the full gist:

https://gist.github.com/mankum93/179c2d5378f27e95742c3f2434de7168