Logging with Retrofit 2

前端 未结 21 1327
春和景丽
春和景丽 2020-11-22 07:33

I\'m trying to get the exact JSON that is being sent in the request. Here is my code:

OkHttpClient client = new OkHt         


        
相关标签:
21条回答
  • 2020-11-22 08:02

    For those who need high level logging in Retrofit, use the interceptor like this

    public static class LoggingInterceptor implements Interceptor {
        @Override public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long t1 = System.nanoTime();
            String requestLog = String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers());
            //YLog.d(String.format("Sending request %s on %s%n%s",
            //        request.url(), chain.connection(), request.headers()));
            if(request.method().compareToIgnoreCase("post")==0){
                requestLog ="\n"+requestLog+"\n"+bodyToString(request);
            }
            Log.d("TAG","request"+"\n"+requestLog);
    
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();
    
            String responseLog = String.format("Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers());
    
            String bodyString = response.body().string();
    
            Log.d("TAG","response"+"\n"+responseLog+"\n"+bodyString);
    
            return response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), bodyString))
                    .build();
            //return response;
        }
    }
    
    public 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";
        }
    }`
    

    Courtesy: https://github.com/square/retrofit/issues/1072#

    0 讨论(0)
  • 2020-11-22 08:02

    Most of the answer here covers almost everything except this tool, one of the coolest ways to see the log.

    It is Facebook's Stetho. This is the superb tool to monitor/log your app's network traffic on google chrome. You can also find here on Github.

    0 讨论(0)
  • 2020-11-22 08:03

    for Retrofit 2.0.2 the code is like

       **HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient.Builder httpClient=new OkHttpClient.Builder();
            httpClient.addInterceptor(logging);**
    
    
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        **.client(httpClient.build())**
                        .build();
            }
    
    0 讨论(0)
  • 2020-11-22 08:04

    First Add dependency to build.gradle:

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

    While using Kotlin you can add Logging Interceptor like this :

    companion object {
        val okHttpClient = OkHttpClient().newBuilder()
                .addInterceptor(HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
                .build()
    
    
        fun getRetrofitInstance(): Retrofit {
            val retrofit = Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(ScanNShopConstants.BASE_URL)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
    
            return retrofit
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:04

    The following set of code is working without any problems for me

    Gradle

    // Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
    

    RetrofitClient

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(logging)
            .build();
    
    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();
    

    One can also verify the results by going into Profiler Tab at bottom of Android Studio, then clicking + sign to Start A New Session, and then select the desired spike in "Network". There you can get everything, but it is cumbersome and slow. Please see image below.

    0 讨论(0)
  • 2020-11-22 08:04

    Here is a simple way to filter any request/response params from the logs using HttpLoggingInterceptor :

    // Request patterns to filter
    private static final String[] REQUEST_PATTERNS = {
        "Content-Type",
    };
    // Response patterns to filter
    private static final String[] RESPONSE_PATTERNS = {"Server", "server", "X-Powered-By", "Set-Cookie", "Expires", "Cache-Control", "Pragma", "Content-Length", "access-control-allow-origin"};
    
    // Log requests and response
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
    
            // Blacklist the elements not required
            for (String pattern: REQUEST_PATTERNS) {
                if (message.startsWith(pattern)) {
                    return;
                }
            }
            // Any response patterns as well...
            for (String pattern: RESPONSE_PATTERNS) {
                if (message.startsWith(pattern)) {
                    return;
                }
            }
            Log.d("RETROFIT", message);
        }
    });
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    

    Here is the full gist:

    https://gist.github.com/mankum93/179c2d5378f27e95742c3f2434de7168

    0 讨论(0)
提交回复
热议问题