Open In App

Android – Enable Logging in OkHttp

Last Updated : 19 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Have you ever experienced a negative experience while doing an API request in your Android application? Or perhaps you encountered an error that rendered your API call ineffective.

What did you attempt?

The first option would have been to try API requests through some client to figure out what was wrong. Or perhaps you would have tried something different. What if we told you that you could have selected something different that would not have forced you to test APIs through a client?

Geek Tip: You may use interceptors in your Android code to obtain the logs when an issue occurs. Isn’t this a better solution?

What Exactly is OkHttp?

OkHttp is an interceptor that allows you to report API requests. So, in this case, an interceptor functions more like a manager for an API request, allowing you to monitor or execute certain actions on your API calls. Let us begin by including it into our project; in the build.gradle file, we will include the following:

implementation "com.squareup.okhttp3:logging-interceptor:4.0.0"

And then, in order to begin tracking your API calls, we must first perform an API request.

Kotlin




val geeksforgeeks = OkHttpClient.Builder()
var demands = Request.Builder()
        .url(/*Your API key which you generated*/)
        .build()


Now, In this section, we build an object for the request and define a variable client of OkHttpClient. 

Hence, in order to make an API request, we will need the following code:

Kotlin




geeksforgeeks.newCall(request).enqueue(object :Callback{
    override fun onFailure(request: Request?, e: IOException?) {
        // The API Call Failed
          // Do something like changing
          // the UI to prompt user
    }
    override fun onResponse(response: Response?) {
        // Response returned from the API
          // So something from it.
    }
})


We have just made our first API call. However, we would not see any logs because we have not installed any interceptors to log the calls. So, how can we record the call’s response?

To begin logging, we must include interceptors in the OkHttpClient described earlier.

And, as previously said, interceptors are used to monitor the API request and will publish the logs that are created in the console’s Logcat. To include an Interceptor:

Kotlin




val aLogger = HttpLoggingInterceptor()
aLogger.level = (HttpLoggingInterceptor.Level.BASIC)


And, in order to include this interceptor in the client we use:

Kotlin




val geeksforgeeks = OkHttpClient.Builder()
geeksforgeeks.addInterceptor(logging)


And now, when we access the API again, we’ll get logs in Logcat that look like this:

--> POST /hello world/http/1.1 (6-byte body)

<-- 600 OK (10ms, 4-byte body)

Some Points To Note

Note #1: To add a custom TAG for your or logs, simply enter the following,

Kotlin




val aLogger = HttpLoggingInterceptor(object : Logger() {
    fun aLogger(textString: String) {
        Log.d("GEEKS FOR GEEKS", textString)
    }
})


Note #2: You may also extend the Interceptor class to construct your own Interceptor.

Kotlin




class GeeksforGeeksInterceptor : Interceptor {
    override fun gfgInter(chain: Interceptor.Chain): Response {
        var geeksforgeeks = chain.request()
        geeksforgeeks = request.newBuilder()
                .build()
        return chain.proceed(request)
    }
}


Then add it to the client’s list by using:

Kotlin




val geeksforgeeks = OkHttpClient.Builder()
geeksforgeeks.addInterceptor(CustomInterceptor())


Conclusion

In the above sample, redactHeader conceals the sensitive information of the Authorization and Cookie key. These are only created at the HEADERS and BODY levels. This is how we can track API calls performed in your Android app.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads