使用改造 2 进行日志记录 [英] Logging with Retrofit 2
问题描述
我正在尝试获取请求中发送的确切 JSON.这是我的代码:
I'm trying to get the exact JSON that is being sent in the request. Here is my code:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor(){
@Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Log.e(String.format("
request:
%s
headers:
%s",
request.body().toString(), request.headers()));
com.squareup.okhttp.Response response = chain.proceed(request);
return response;
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client).build();
但我只在日志中看到这一点:
But I only see this in the logs:
request:
com.squareup.okhttp.RequestBody$1@3ff4074d
headers:
Content-Type: application/vnd.ll.event.list+json
如果删除了我们过去用于 Retrofit 1 的 setLog()
和 setLogLevel()
,我应该如何进行正确的日志记录?
How am I supposed to do proper logging, given the removal of setLog()
and setLogLevel()
which we used to use with Retrofit 1?
推荐答案
在 Retrofit 2 中你应该使用 HttpLoggingInterceptor.
In Retrofit 2 you should use HttpLoggingInterceptor.
向 build.gradle
添加依赖项.截至 2019 年 10 月的最新版本是:
Add dependency to build.gradle
. Latest version as of October 2019 is:
implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'
创建一个 Retrofit
对象,如下所示:
Create a Retrofit
object like the following:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://backend.example.com")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(ApiClient.class);
如果出现弃用警告,只需将 setLevel
更改为:
In case of deprecation warnings, simply change setLevel
to:
interceptor.level(HttpLoggingInterceptor.Level.BODY);
上述解决方案为您提供的 logcat 消息与由
The above solution gives you logcat messages very similar to the old ones set by
setLogLevel(RestAdapter.LogLevel.FULL)
如果java.lang.ClassNotFoundException
:
较旧的 Retrofit 版本可能需要较旧的 logging-interceptor
版本.查看评论部分了解详细信息.
Older Retrofit version might require an older logging-interceptor
version. Take a look at comments sections for details.
这篇关于使用改造 2 进行日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!