将日志记录添加到 Retrofit2

可以使用截取器记录改造请求。有几个级别的细节:NONE,BASIC,HEADERS,BODY。在这里查看 Github 项目

  1. 向 build.gradle 添加依赖项:
compile 'com.squareup.okhttp3:logging-interceptor:3.8.1'
  1. 创建 Retrofit 时添加日志记录拦截器:
  HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
  loggingInterceptor.setLevel(LoggingInterceptor.Level.BODY);
  OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
          .addInterceptor(loggingInterceptor)
          .build();
  Retrofit retrofit = new Retrofit.Builder()
          .baseUrl("http://example.com/")
          .client(okHttpClient)
          .addConverterFactory(GsonConverterFactory.create(gson))
          .build();

在发布版本中应该避免将日志暴露在终端(Android 监视器)中,因为它可能会导致不必要地暴露关键信息,例如 Auth Tokens 等。

要避免在运行时暴露日志,请检查以下条件

if(BuildConfig.DEBUG){
     //your interfector code here   
    }

例如:

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
if(BuildConfig.DEBUG){
     //print the logs in this case   
    loggingInterceptor.setLevel(LoggingInterceptor.Level.BODY);
}else{
    loggingInterceptor.setLevel(LoggingInterceptor.Level.NONE);
}

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
      .addInterceptor(loggingInterceptor)
      .build();

Retrofit retrofit = new Retrofit.Builder()
      .baseUrl("http://example.com/")
      .client(okHttpClient)
      .addConverterFactory(GsonConverterFactory.create(gson))
      .build();