印出 API 的 Log--OkHttp HttpLoggingInterceptor (Retrofit 適用)
介紹 以往為了檢查 API 呼叫的 Request 或 Response 是否正確,都是土法煉鋼式的自行加註 Log。後來改用 Retrofit 之後,發現要加 Log 變得好麻煩,這才發現原來有 HttpLoggingInterceptor 可以自動印 Log 。 Java Doc: HttpLoggingInterceptor How to log request and response body with Retrofit-Android? 👀 OkHttp 的 Interceptors 介面有許多實作的類別,可以針對 API 呼叫做很多不一樣的事情,有興趣的讀者可以多利用這個關鍵字下去尋找相關的資料,本篇文章就不贅述。 使用 1. add gradle dependency 1 implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0' 🚨 注意! 套件引用的版本,請以官方最新版本為準。 2. 新增 HttpLoggingInterceptor 到 OkHttpClient 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 private fun getOkHttpClient(): OkHttpClient { val loggingInterceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().setLevel( if (BuildConfig.DEBUG) { // Debug 模式下才開啟 HttpLoggingInterceptor.Level.BODY } else { HttpLoggingInterceptor.Level.NONE } ) return OkHttpClient.Builder() .addInterceptor(loggingInterceptor) // ... .build() } 3. 正常呼叫 API Logcat 就會出現相關的 Log 囉 Level.NONE 什麼都不印 ...