Logging in Retrofit 2 using okhttp

RETROFIT allows integration of a lot of add on libraries like converters, libraries for other network operations etc. One such library is the OKHTTP library. OKHTTP is one efficient library when it comes to handling network operations. It can easily be attached to retrofit. Hence even if retrofit doesn't allow any default methods for logging, we can add an okhttp client enabled with logging to the retrofit instance to support logging.

Add this dependency in your app's build.gradle file

compile 'com.squareup.okhttp3:logging-interceptor:3.9.1'


Now you need to create an instance of the logging interceptor like this

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);

you may set the log level**  as NONE,BASIC,HEADERS,BODY

Now create an okhttp client instance and then add this interceptor to it

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(interceptor);
Now set the httpClient to your retrofit instance like this

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("base_url")
        .client(httpClient.build())
        .build();

now run the app and check your logcat to see log messages like shown below



The setLevel method is used for setting the level of log i.e,

HttpLoggingInterceptor.Level.NONE - No logs will be produced(ideal for production environments)

HttpLoggingInterceptor.Level.BASIC - Logs request and response lines.example :
--> POST /greeting http/1.1 (3-byte body)** <-- 200 OK (22ms, 6-byte body)
HttpLoggingInterceptor.Level.HEADERS - Logs request and response lines and their respective headers.
example :

 --> POST /greeting http/1.1* Host: example.com* Content-Type: plain/text* Content-Length: 3* --> END POST** <-- 200 OK (22ms)* Content-Type: plain/text* Content-Length: 6* <-- END HTTP

HttpLoggingInterceptor.Level.BODY - Logs request and response lines and their respective headers and bodies (if present)example :
 --> POST /greeting http/1.1* Host: example.com* Content-Type: plain/text* Content-Length: 3** Hi?* --> END POST** <-- 200 OK (22ms)* Content-Type: plain/text* Content-Length: 6** Hello!* <-- END HTTP

1 comment: