Logging with Retrofit 2
Here is an Interceptor
that logs both the request and response bodies (using Timber, based on an example from the OkHttp docs and some other SO answers):
public class TimberLoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Timber.i("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers());
Timber.v("REQUEST BODY BEGIN\n%s\nREQUEST BODY END", bodyToString(request));
Response response = chain.proceed(request);
ResponseBody responseBody = response.body();
String responseBodyString = response.body().string();
// now we have extracted the response body but in the process
// we have consumed the original reponse and can't read it again
// so we need to build a new one to return from this method
Response newResponse = response.newBuilder().body(ResponseBody.create(responseBody.contentType(), responseBodyString.getBytes())).build();
long t2 = System.nanoTime();
Timber.i("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers());
Timber.v("RESPONSE BODY BEGIN:\n%s\nRESPONSE BODY END", responseBodyString);
return newResponse;
}
private static String bodyToString(final Request request){
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e) {
return "did not work";
}
}
}
I met the thing as you and I tried to ask the author of the book Retrofit: Love working with APIs on Android (here is the link) (nope! I am not making some ads for them....but they are really nice guys :) And the author replied to me very soon, with both Log method on Retrofit 1.9 and Retrofit 2.0-beta.
And here is the code of Retrofit 2.0-beta:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(Level.BODY);
OkHttpClient httpClient = new OkHttpClient();
// add your other interceptors …
// add logging as last interceptor
httpClient.interceptors().add(logging); // <-- this is the important line!
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
This is how to add logging method with the help of HttpLoggingInterceptor. Also if you are the reader of that book I mentioned above, you may find that it says there is not log method with Retrofit 2.0 anymore -- which, I had asked the author, is not correct and they will update the book next year talking about it.
// In case you are not that familiar with the Log method in Retrofit, I would like to share something more.
Also should be noticed that there are some Logging Levels you could pick. I use the Level.BODY most of the time, which will give some thing like this:
You can find almost all the http staff inside the picture: the header, the content and response, etc.
And sometimes you really don't need all the guests to attend your party: I just want to know whether it's successfully connected, that internet call is successfully made within my Activiy & Fragmetn. Then you are free to use Level.BASIC, which will return something like this:
Can you find the status code 200 OK inside? That is it :)
Also there is another one, Level.HEADERS, which will only return the header of the network. Ya of course another picture here:
That's all of the Logging trick ;)
And I would like to share you with the tutorial I learned a lot there. They have a bunch of great post talking about almost everything related to Retrofit, and they are continuing updating the post, at the same time Retrofit 2.0 is coming. Please take a look at those work, which I think will save you lots of time.
In Retrofit 2 you should use HttpLoggingInterceptor.
Add dependency to build.gradle
. Latest version as of October 2019 is:
implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'
Create a Retrofit
object like the following:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://backend.example.com")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(ApiClient.class);
In case of deprecation warnings, simply change setLevel
to:
interceptor.level(HttpLoggingInterceptor.Level.BODY);
The above solution gives you logcat messages very similar to the old ones set by
setLogLevel(RestAdapter.LogLevel.FULL)
In case of java.lang.ClassNotFoundException
:
Older Retrofit version might require an older logging-interceptor
version. Take a look at comments sections for details.
The main problem which I faced was dynamical adding headers and logging them into debug logcat. I've tried to add two interceptors. One for logging and one for adding headers on-the-go (token authorization). The problem was that we may .addInterceptor or .addNetworkInterceptor. As Jake Wharton said to me: "Network interceptors always come after application interceptors. See https://github.com/square/okhttp/wiki/Interceptors". So here is working example with headers and logs:
OkHttpClient httpClient = new OkHttpClient.Builder()
//here we can add Interceptor for dynamical adding headers
.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("test", "test").build();
return chain.proceed(request);
}
})
//here we adding Interceptor for full level logging
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(httpClient)
.baseUrl(AppConstants.SERVER_ADDRESS)
.build();