OkHttp忽略日志拦截器

时间:2018-06-25 12:23:19

标签: android retrofit2 okhttp3

我遇到了一个奇怪的问题。 OkHttp给我这样的日志:

  

I / System.out:[OkHttp] sendRequest >>

     

I / System.out:[OkHttp] sendRequest <<< / p>

但是我在客户端初始化中声明了日志记录拦截器。

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);

OkHttpClient.Builder client = new OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .addInterceptor(chain -> {
            Request original = chain.request();
            Request.Builder builder = original.newBuilder()
                    .header("Authorization", Credentials.basic(config.login(), config.password()));
            Request request = builder.build();
            return chain.proceed(request);
        })
        .addInterceptor(httpLoggingInterceptor);

return new Retrofit.Builder()
        .baseUrl(config.getServer())
        .callbackExecutor(Executors.newSingleThreadExecutor())
        .addConverterFactory(getMoshiConverterFactory())
        .client(client.build())
        .build();

我的成绩包含:

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.3.0'
implementation 'com.squareup.moshi:moshi:1.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.7.0'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.7.0'

我做错什么了吗?

4 个答案:

答案 0 :(得分:2)

HttpLoggingInterceptor logger = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            Log.d("OkHttp", message);
        }
    });

尝试这种方式。

答案 1 :(得分:2)

您可以将其用作网络拦截器,而不是应用程序拦截器。用.addNetworkInterceptor(httpLoggingInterceptor);代替.addInterceptor(httpLoggingInterceptor);

这使您可以“观察数据,就像通过网络传输数据一样”。

查看更多信息in the wiki pages.

答案 2 :(得分:0)

一段时间后,我确定了此Sony设备显示的日志,并在替换后的okhttp-logging-interceptor上进行了复制

Platform.get().log(INFO, message, null);

使用

Log.i("Retrofit", message)

因为设备显示仅来自应用程序的System.outLog.iLog.wLog.e日志。

答案 3 :(得分:0)

我遇到了同样的问题,并在Github上找到了这篇文章,可以帮助我解决问题。

https://github.com/square/okhttp/issues/3985#issuecomment-465505085

在简历中,某些设备默认情况下(即使启用了开发人员选项)也不记录详细信息和调试消息。

检查设备的构建属性会得到以下结果:

adb shell getprop log.tag

使用adb shell setprop log.tag VERBOSE将I更改为V(或仅为VERBOSE)后:

注意:重新启动手机时,此设置可能不会保留!

所以这不是OkHttp问题,而是某些设备上的系统设置。