OkHttp Interceptors in Android

May 25 2021 · Kotlin 1.4, Android 5, Android Studio 4.1

Part 1: Implementing OkHttp Interceptors

04. Implement a Custom Logger & Redact Headers

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 03. Setup HttpLoggingInterceptor & Debug API Calls Next episode: 05. Implement an Authorization Interceptor

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 04. Implement a Custom Logger & Redact Headers

HttpLoggingInterceptor, by default, uses the Android logging utility to log all network data. But you can easily modify this behavior. Open the app module build.gradle. Here you can find the dependency for the Timber library.

Timber is a popular logging library that provides flexibility on how you log data. Open OkHttpProvider and place your cursor inside HttpLoggingInterceptor’s constructor. To view information about the parameters, click Command + P on Mac (or Ctrl + P on Windows).

You can see that the constructor takes an instance of HttpLoggingInterceptor.Logger as as a parameter. Add an instance of HttpLoggingInterceptor.Logger to the HttpLoggingInterceptor constructor and implement the method required.

val loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
    override fun log(message: String) {
        
    }
})

Now you can use any logging client of your choice to the log intercepted data. For this project, use Timber to log the message as follows:

Timber.tag("OkHttp").d(message)

This line of code uses OkHttp as the log tag and logs the message as debug data. Android Studio suggests that you convert the interface implementation to a lambda. Go ahead and convert it.

val loggingInterceptor = HttpLoggingInterceptor { message -> Timber.tag("OkHttp").d(message) }

Open the Logcat tab and verify that the data is being logged with the correct tag.

When logging network data, avoid logging sensitive information that is sometimes passed as headers. Such headers can contain API keys, authentication tokens, etc. In this example, consider that x-amz-cf-id is sensitive data and you want to avoid logging it.

When you redact the header, you will no longer be able to view the header value.

Inside the getOkHttpClient method, add the following line of code:

loggingInterceptor.redactHeader("x-amz-cf-id")

The line above tells HttpLoggingInterceptor that whenever a header named x-amz-cf-id is present, it should be redacted. Build and run the app.

Open the Logcat tab. You will now notice that the header named x-amz-cf-id has been redacted.