HttpLoggingInterceptor 不记录改造 2

HttpLoggingInterceptor not logging with retrofit 2

我正在尝试使用 refrofit2、kotlin 和日志记录拦截器记录所有请求(使用网络拦截器):

赞:

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

    val okHttpClient = OkHttpClient.Builder()
        .addNetworkInterceptor(interceptor) // same for .addInterceptor(...)
        .connectTimeout(30, TimeUnit.SECONDS) //Backend is really slow
        .writeTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build()

    sRestAdapter = Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl(if (host.endsWith("/")) host else "$host/")
        .addConverterFactory(GsonConverterFactory.create(gson()))
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build()

它只是打印:

D/OkHttp: --> GET url...
D/OkHttp: --> END GET

发生了什么事?

----------------编辑--------

记录器不会显示在主线程上执行请求的错误,所以要小心。

而不是

val okHttpClient = OkHttpClient.Builder()
    .addNetworkInterceptor(interceptor)
    ...

你应该有这样的东西:

val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(interceptor)
    ...

因为 addNetworkInterceptor() 使用观察单个网络请求和响应的拦截器,而 addInterceptor() 添加观察每个调用的完整跨度的拦截器:从建立连接(如果有)直到选择了响应源(源服务器、缓存或两者)。

编辑

Errors doing requests on Main Thread are not showing by the logger, so be careful

在主线程上进行联网不是 "ordinary" 错误。这将导致您的应用程序被系统以 NetworkOnMainThreadException 杀死,这将在拦截器有机会 运行.

之前发生
private val interceptor = run {
    val httpLoggingInterceptor = HttpLoggingInterceptor()
    httpLoggingInterceptor.apply {
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
    }
}


private val okHttpClient = OkHttpClient.Builder()
    .addNetworkInterceptor(interceptor) // same for .addInterceptor(...)
    .connectTimeout(30, TimeUnit.SECONDS) //Backend is really slow
    .writeTimeout(30, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .build()