我们知道,Retrofit是基于OkHttp发展而来,因此在Retrofit中设置日志打印,就是在OkHttp设置。
1、添加依赖
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
2、添加打印代码
HttpLoggingInterceptor:http日志拦截器
方法1:自定义输出日志格式
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
try {
String text = URLDecoder.decode(message, "utf-8");
Log.e("OKHttp-----", text);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("OKHttp-----", message);
}
}
});
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// 四个级别:NONE,BASIC,HEADER,BODY
// BASEIC:请求/响应行
// HEADER:请求/响应行 + 头
// BODY:请求/响应航 + 头 + 体
mClient = new OkHttpClient.Builder().addInterceptor(interceptor).build();
方法2:默认打印输出如下
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(1000L, TimeUnit.MILLISECONDS)
.readTimeout(1000L, TimeUnit.MILLISECONDS)
.writeTimeout(1000L, TimeUnit.MILLISECONDS)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
}
})
.addInterceptor(logging)//添加日志拦截器
.build();
效果如图:
以上是很多人采取的做法,但总感觉显示效果看起来费劲。来个优雅的姿势:
请看实现代码:GitHub
Gradle:需要替换依赖模块
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
compile('com.github.ihsanbal:LoggingInterceptor:3.0.0') {
exclude group: 'org.json', module: 'json'
}
}
开始使用:注意loggable(BuildConfig.DEBUG),“其他问题”会提及。
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.addInterceptor(new LoggingInterceptor.Builder()
.loggable(BuildConfig.DEBUG)
.setLevel(Level.BASIC)
.log(Platform.INFO)
.request("Request")
.response("Response")
.addHeader("version", BuildConfig.VERSION_NAME)
.addQueryParam("query", "0")
.enableMock(true, 1000L, request -> {
String segment = request.url().pathSegments().get(0);
return Okio.buffer(Okio.source(mAssetManager.open(String.format("mock/%s.json", segment)))).readUtf8();
})
// .enableAndroidStudio_v3_LogsHack(true) /* enable fix for logCat logging issues with pretty format */
// .logger(new Logger() {
// @Override
// public void log(int level, String tag, String msg) {
// Log.w(tag, msg);
// }
// })
// .executor(Executors.newSingleThreadExecutor())
.build());
OkHttpClient okHttpClient = client.build();
//You can use with Retrofit
Retrofit retrofitAdapter = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl("https://.../")
.client(okHttpClient)
.build();
Level:设置显示级别
setLevel(Level.BASIC)
.NONE // No logs
.BASIC // Logging url,method,headers and body.
.HEADERS // Logging headers
.BODY // Logging body
Platform
loggable(BuildConfig.DEBUG) // enable/disable sending logs output.
log(Platform.WARN) // setting log type
Tag:设置标签
tag("LoggingI") // Request & response each log tag
request("request") // Request log tag
response("response") // Response log tag
Header:自定义头部
addHeader("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 ") // Adding to request
其他问题:
-
按照上述步骤引用后,发现日志没有打印输出
产生原因:经过断点 LoggingInterceptor 调试发现:BuildConfig.DEBUG = false 导致无法打印 - 用到知识点:
1、所有Module 都会在编译时自动生成一个BuildConfig.java类,类路径为所在Module的包名。
2、被依赖的 Module 默认会提供 Release 版的BuildConfig类给主Module使用(即BuildConfig.DEBUG = false),
3、在下图代码中,只有com.lvxiangan.rxjavasamples.BuildConfig 的Debug值为true,其他都是false -
解决方法:
方法1:引入正确的类路径,即:com.lvxiangan.rxjavasamples.BuildConfig
方法2:把 loggable(BuildConfig.DEBUG) 改成 loggable(true)
哈哈……