將日誌記錄新增到 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();