Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging in Retrofit 2.0

Previous version of Retrofit uses RestAdapter and has provision of enabling the Logs. Why that feature is removed in Retrofit 2.0?

To enable log, I have to do..

 Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    /** Handles Log */
    retrofit.client().interceptors().add(new LoggingInterceptor());


class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    Logger.d(String.format("Sending request %s on %s%n%s",
            request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    Logger.d(String.format("Received response for %s in %.1fms%n%s",
            response.request().url(), (t2 - t1) / 1e6d, response.headers()));

   // Logger.d(""+new String(response.body().bytes()));
    return response;
}

This is the Only solution for this? Previous provision was very handy...

like image 613
sreekumar Avatar asked Sep 27 '22 12:09

sreekumar


2 Answers

Intention of Retrofit is to perform type safe de/serialization. Probably it has dropped features that should be performed by the http client, like it is the logging.

Reasonably, the http client should be logging the responses received rather than Retrofit. Your question is too broad, the guys from Square should add more.

like image 86
Nikola Despotoski Avatar answered Sep 29 '22 07:09

Nikola Despotoski


For logging in retrofit 2 okhttp has the following logger:

 private OkHttpClient getOkHttpClient() {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    if (BuildConfig.LOG_HTTP_CALLS) {
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    }

    return new OkHttpClient.Builder()
            .addInterceptor(logging).build();
}

and the dependency in build.gradle is

compile 'com.squareup.okhttp3:logginginterceptor:2.1.0'

like image 34
UDI Avatar answered Sep 29 '22 06:09

UDI