OkHttp忽略日志拦截器

3

我遇到了一个奇怪的问题。 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'

我做错了什么吗?

4个回答

3
您可以将其作为网络拦截器而不是应用程序拦截器使用。请使用.addNetworkInterceptor(httpLoggingInterceptor);而不是.addInterceptor(httpLoggingInterceptor); 这样可以让您“观察数据,就像它将在网络上传输一样”。
更多信息请参见wiki页面。

有趣的回答,但没有帮助。我不知道,可能是因为设备的问题,但我没有其他设备。作为一名真正的Android开发者,我只有iPhone,而且模拟不支持我的临时电脑。 - Anton A.

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

尝试这种方法。

0

经过一段时间的研究,我弄清楚了这个Sony设备显示哪些日志并制作了一个okhttp-logging-interceptor的副本,其中我进行了替换。

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

使用

Log.i("Retrofit", message)

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


0

我曾经遇到同样的问题,后来在 Github 上找到了这篇帖子,帮助我解决了这个问题。

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

简而言之,一些设备默认情况下(即使开启了开发者选项)不记录详细和调试信息。
检查设备的构建属性会得到以下结果:
adb shell getprop log.tag I
将 I 更改为 V(或仅 VERBOSE)使用 adb shell setprop log.tag VERBOSE:
注意:重新启动手机时可能无法保留此设置!
因此,这不是 OkHttp 的问题,而是某些设备上的系统设置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接