OkHttp 忽略日志记录拦截器

OkHttp ignore logging interceptor

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

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

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

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

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();

我的 gradle 包含:

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'

我是不是做错了什么?

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

试试这个方法。

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

这让你 "Observe the data just as it will be transmitted over the network"。

查看更多信息in the wiki pages.

一段时间后,我弄清楚了这个 Sony 设备显示的日志,并复制了 okhttp-logging-interceptor 并替换了

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

Log.i("Retrofit", message)

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

我遇到了同样的问题并在 Github 上找到了这个 post 帮助我解决了问题。

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

在恢复中,某些设备默认情况下(即使开发者选项处于打开状态)不会记录详细信息和调试信息。

检查设备的构建属性给出以下结果:

adb shell getprop log.tag

I

在使用 adb shell setprop log.tag VERBOSE:

将 I 更改为 V(或只是 VERBOSE)之后

注意:重新启动 phone!

时,此设置可能不会保留

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