Home >Java >javaTutorial >How to Implement HTTP Logging in Retrofit 2?
Logging in Retrofit 2
In Retrofit 2, logging has been enhanced by providing more control over the level of detail in the logs. To enable logging, you can use the HttpLoggingInterceptor.
Implementation:
Add the dependency to your build.gradle file:
implementation 'com.squareup.okhttp3:logging-interceptor:4.11.0'
Create a HttpLoggingInterceptor and specify the desired logging level:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.level(HttpLoggingInterceptor.Level.BODY);
Create an OkHttpClient and add the interceptor:
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Use the OkHttpClient to build your Retrofit instance:
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://backend.example.com") .client(client) .addConverterFactory(GsonConverterFactory.create()) .build();
With this setup, you will get detailed logs in your logcat, including the exact JSON payload sent in the request.
The above is the detailed content of How to Implement HTTP Logging in Retrofit 2?. For more information, please follow other related articles on the PHP Chinese website!