在 Kotlin 中使用 Logger 打印 OkHttp 網絡請求返回的 Logcat 日誌

在做 Android 開發的時候,好的日誌輸出,能夠快速定位問題所在。之前在使用 Java 開發 Android 的時候,我使用的是這個庫: orhanobut/logger
在這裏插入圖片描述
現在使用 Kotlin 開發 Android ,還想繼續使用這個庫,而開發階段常見的日誌輸出是 將接口返回的結果打印出來,下面就介紹如何在 Kotlin 項目中接入 logger庫。

集成

module下的 build.gradle中添加

implementation 'com.orhanobut:logger:2.2.0'

接着在 application 中初始化

Logger.addLogAdapter(AndroidLogAdapter())

application中還可以對logger進行一些高級的配置

val formatStrategy = PrettyFormatStrategy.newBuilder()
   .showThreadInfo(false)  // 輸出線程信息. 默認輸出
   .methodCount(0)         // 方法棧打印的個數,默認是2
   .methodOffset(7)        // 設置調用堆棧的函數偏移值,0的話則從打印該Log的函數開始輸出堆棧信息,默認是0
   .logStrategy(LogCatStrategy())
   .build()
Logger.addLogAdapter(AndroidLogAdapter(formatStrategy))

LogCatStrategy 策略是解決 AndroidStudio logcat 日誌換行問題

class LogCatStrategy: LogStrategy {
    override fun log(priority: Int, tag: String?, message: String) {
        Log.println(priority, randomKey() + tag!!, message)
    }

    private var last: Int = 0

    private fun randomKey(): String {
        var random = (10 * Math.random()).toInt()
        if (random == last) {
            random = (random + 1) % 10
        }
        last = random
        return random.toString()
    }
}

基本使用

Logger.d("debug");
Logger.e("error");
Logger.w("warning");
Logger.v("verbose");
Logger.i("information");
Logger.wtf("What a Terrible Failure");

查看項目主頁 orhanobut/logger README有詳細介紹。

輸出網絡日誌

前提是 OkHttp 網絡請求庫已經集成。可以參考我的組件化框架項目:FrameDemo 裏面的網絡請求集成。

網絡請求使用的是 OkHttp

com.squareup.okhttp3:okhttp:4.0.0

日誌攔截使用的是logging-interceptor

com.squareup.okhttp3:logging-interceptor:4.0.0

在 OkHttp 中使用 logger 輸出日誌只需要簡單幾步即可

  1. 在 OkHttp 中添加攔截器(重點看中文註釋部分即可)
private fun getOkHttpClient(): OkHttpClient {
        val cacheFile = File(BaseApplication.context.cacheDir, "cache")
        val cache = Cache(cacheFile, 1024 * 1024 * 50) 
        // 創建日誌攔截器 HttpLogger() 是自定義的類
        val logInterceptor = HttpLoggingInterceptor(HttpLogger())
        logInterceptor.level = HttpLoggingInterceptor.Level.BODY
        
        return OkHttpClient.Builder()
            .cache(cache) 
            .connectTimeout(60L, TimeUnit.SECONDS)
            .readTimeout(60L, TimeUnit.SECONDS)
            .writeTimeout(60L, TimeUnit.SECONDS)
            .cookieJar(PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(BaseApplication.context)))
            .addInterceptor(ChangeBaseUrlInterceptor())
            .addInterceptor(CacheInterceptor())
            // 添加日誌攔截攔截器
            .addNetworkInterceptor(logInterceptor)
            .addInterceptor(CheckLoginInterceptor())
            .build()
    }
  1. 在自定義的類中將日誌打印出來 (相關工具類可在 FrameDemo 項目的lib_common 模塊下的 utils包下找到)
class HttpLogger: HttpLoggingInterceptor.Logger {
    override fun log(message: String) {
        var msg = message

        // 以{}或者[]形式的說明是響應結果的json數據,需要進行格式化
        if ((msg.startsWith("{") && msg.endsWith("}"))
            || (msg.startsWith("[") && msg.endsWith("]"))) {
            msg = JsonUtils.formatJson(JsonUtils.decodeUnicode(msg))
        }
        LogUtils.d(msg)
    }
}

在這裏插入圖片描述
PS:圖中紅色框中的按鈕不要選中,不然會出現日誌格式化失敗。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章