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.