19

I am using retrofit 2.x and i want to log the header and body of request and response .

  HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
            .addNetworkInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Request request = chain.request().newBuilder()
                            .addHeader("key", "value")
                            .addHeader("HEADER","HEADER Value")
                            .build();
                    return chain.proceed(request);
                }


            }).build();

And this how i am doing,my problem is header of request are not being logged in Android Monitor but rest everything is logged .

Gradle Version

 compile ('com.squareup.retrofit2:retrofit:2.0.0-beta3') {
    // exclude Retrofit’s OkHttp peer-dependency module and define your own module import
    exclude module: 'okhttp'
}
compile 'com.squareup.okhttp3:okhttp:3.0.0-RC1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta3'
compile ('com.squareup.okhttp3:logging-interceptor:3.0.1'){
    exclude module: 'okhttp'
}

Using RC1 and 3.0.1 due to bug issue reported Bug Link

Code_Life
  • 5,742
  • 4
  • 29
  • 49
  • Have you tried moving the logging interceptor to the last position, i. e. below the interceptor that adds he header? According to the docs: `...interceptors are called in order.` Maybe the response is just logged before the headers are added? – david.mihola Feb 08 '16 at 14:05
  • @david.mihola : i tried .. but it didn't work . – Code_Life Feb 08 '16 at 18:34
  • as an alternative, you may use facebook's stetho library http://facebook.github.io/stetho/ – chubao Feb 26 '16 at 14:25
  • http://stackoverflow.com/questions/33141407/logging-in-retrofit-2-0/38890345#38890345 – Nilesh Senta Aug 11 '16 at 07:49

6 Answers6

33

Oh I found the error if anyone is interested :

 HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(interceptor)
        .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
        .addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder()
                        .addHeader("key", "value")
                        .addHeader("HEADER","HEADER Value")
                        .build();
                return chain.proceed(request);
            }


        }).build();

You must add the log interceptor (your interceptor variable) after the request interceptor, so the correct answer is:

 HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws 
 IOException {
                Request request = chain.request().newBuilder()
                        .addHeader("key", "value")
                        .addHeader("HEADER","HEADER Value")
                        .build();
                return chain.proceed(request);
            }


        })
        .addInterceptor(interceptor)
        .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
        .build();
diegoveloper
  • 93,875
  • 20
  • 236
  • 194
  • 4
    Crazy that it does not state this clearly or that it's not handling all orders... Thanks! :) – Otziii Apr 02 '19 at 13:37
11

Instead of using addInterceptor to add the logging interceptor, use addNetworkInterceptor, to include headers added by OkHttp.

Network interceptors are able to:

Observe the data just as it will be transmitted over the network.

reacuna
  • 463
  • 9
  • 17
10

May it help someone ...

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

Add both to see complete logs and add this interceptor at the last (don't know why but its like this).

MatheusJardimB
  • 3,599
  • 7
  • 46
  • 70
Code_Life
  • 5,742
  • 4
  • 29
  • 49
  • 6
    You don't need to add both and it is basically useless. Setting `BODY` only should show all headers and bodies logs. https://github.com/square/okhttp/blob/master/okhttp-logging-interceptor/src/main/java/okhttp3/logging/HttpLoggingInterceptor.java#L132 – oldergod Jan 12 '17 at 00:12
  • @oldergod : Yes, I agree with you with but this what it was at 2016. :) – Code_Life Jan 28 '18 at 04:45
3

You need to set following:

   OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
   HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
   httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
   clientBuilder.addNetworkInterceptor(httpLoggingInterceptor);
   clientBuilder.build()
Mladen Rakonjac
  • 9,562
  • 7
  • 42
  • 55
1

The following link was very useful: https://medium.com/swlh/okhttp-interceptors-with-retrofit-2dcc322cc3f3

OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();

//Gson Builder
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Timber.plant(new Timber.DebugTree());

// HttpLoggingInterceptor
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(message -> Timber.i(message));
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);


/**
 * injection of interceptors to handle encryption and decryption
 */

//Encryption Interceptor
EncryptionInterceptor encryptionInterceptor = new EncryptionInterceptor(new EncryptionImpl());
//Decryption Interceptor
DecryptionInterceptor decryptionInterceptor = new DecryptionInterceptor(new DecryptionImpl());


// OkHttpClient. Be conscious with the order
OkHttpClient okHttpClient = new OkHttpClient()
    .newBuilder()
    //httpLogging interceptor for logging network requests
    .addInterceptor(httpLoggingInterceptor)
    //Encryption interceptor for encryption of request data
    .addInterceptor(encryptionInterceptor)
    // interceptor for decryption of request data
    .addInterceptor(decryptionInterceptor)
    .build();

//Retrofit
Retrofit retrofit = new Retrofit.Builder()
    .client(okHttpClient)
    .baseUrl(BASE_URL)
    // for serialization
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build();

//ApiService
apiService = retrofit.create(ApiService.class);
Chris Sprague
  • 3,158
  • 33
  • 24
0

You need to add this lib if not added.

implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2

use logger interceptor with level Body for all Log.

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

And add it to your http client. By default level is NONE. FYI

enum class Level {
    /** No logs. */
    NONE,

    /**
     * Logs request and response lines.
     *
     * Example:
     * ```
     * --> POST /greeting http/1.1 (3-byte body)
     *
     * <-- 200 OK (22ms, 6-byte body)
     * ```
     */
    BASIC,

    /**
     * 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
     * ```
     */
    HEADERS,

    /**
     * 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
     * ```
     */
    BODY
  }
Upendra Shah
  • 2,218
  • 17
  • 27