Kotlin的LogUtil

xiasuhuei321發表於2017-12-13

最近在擼東西,除錯的時候用Android原生的Log感覺很不爽,打的Log給我一種東倒西歪,凌亂的感覺。於是自己看了一下Blankj大神的Android-Utils庫,看了一下他實現的LogUtils,借鑑了一下,簡單的封裝了一個在Kotlin中可以正確使用的LogUtil。不過話說講道理,有擴充套件,Util這種東西還是可以儘量不用的,但是我有點不清楚Log這玩意該擴充套件給誰呢,Any?所以還是寫了一個LogUtil……

列印效果

最後直接放一下列印Log的樣子,這裡只放出i級別的日誌:

效果圖

處理了日誌比較長的時候的情況,點選log中藍色的字可以跳轉到程式碼中的相應位置,各位如果感興趣是怎麼實現的,可以直接看我程式碼(當然了,我也是看別人的才知道怎麼去實現,哈哈)。

Blankj大神的LogUtils有一個問題,就是程式碼中獲取程式碼檔案的時候寫死了.java結尾,所以在kotlin以.kt結尾的時候,就無法正確的跳轉到程式碼裡(版本號:1.8.3),當然了,我已經跟Blankj反饋了,在不久的將來應該會修復。

完整程式碼

import android.util.Log
import java.util.*

/**
 * Created by xiasuhuei321 on 2017/9/1.
 * author:luo
 * e-mail:xiasuhuei321@163.com
 */
object LogUtil {
    private val MIN_STACK_OFFSET = 3

    var defaultTag = "LogUtil"
    private val lineSeparator = System.getProperty("line.separator", "/n")

    val V = Log.VERBOSE
    val D = Log.DEBUG
    val I = Log.INFO
    val W = Log.WARN
    val E = Log.ERROR
    val A = Log.ASSERT

    private val TOP_BORDER = "╔═══════════════════════════════════════════════════════════════════════════════════════════════════"
    private val LEFT_BORDER = "║ "
    private val BOTTOM_BORDER = "╚═══════════════════════════════════════════════════════════════════════════════════════════════════"
    private val MAX_LEN = 1000
    var open = true

    private fun processTagAndHead(): String {
        val elements = Thread.currentThread().stackTrace
        val offset = getStackOffset(elements)
        val targetElement = elements[offset]
        val head = Formatter()
                .format("%s [%s(%s:%d)]",
                        "In Thread: " + Thread.currentThread().name,
                        targetElement.methodName,
                        targetElement.fileName,
                        targetElement.lineNumber)

        return head.toString()
    }

    private fun processMsgBody(msg: String, flag: Int, tag: String = defaultTag) {
        printTop(flag, tag)
        // 首先列印呼叫資訊
        printLog(flag, tag)

        val lineCount = msg.length / MAX_LEN
        if (lineCount == 0) {
            printLog(flag, tag, msg)
        } else {
            var index = 0
            var i = 0
            while (true) {
                printLog(flag, tag, msg.substring(index, index + MAX_LEN))
                index += MAX_LEN
                if ((++i) >= lineCount)
                    break
            }
        }
        printBottom(flag, tag)
    }

    fun getStackOffset(trace: Array<StackTraceElement>): Int {
        var i = MIN_STACK_OFFSET
        while (i < trace.size) {
            val e = trace[i]
            val name = e.className
            if (name != LogUtil::class.java.name) {
                return i
            }
            i++
        }
        return 2
    }

    /* 雖然 kotlin 有預設值這種操作,但是 Log.i(tag,msg) 這種比較符合平時的操作,所以還是提供類似的過載,
     * 而非 LogUtil.i(msg: String,tag: String = defaultTAG) 這種帶預設值引數的方法 */

    fun v(msg: String) {
        v(defaultTag, msg)
    }

    fun i(msg: String) {
        i(defaultTag, msg)
    }

    fun d(msg: String) {
        d(defaultTag, msg)
    }

    fun w(msg: String) {
        w(defaultTag, msg)
    }

    fun e(msg: String) {
        e(defaultTag, msg)
    }

    fun v(tag: String, msg: String) {
        if (!open) {
            return
        }
        processMsgBody(msg, V, tag)
    }

    fun i(tag: String, msg: String) {
        if (!open) {
            return
        }
        processMsgBody(msg, I, tag)
    }

    fun d(tag: String, msg: String) {
        if (!open) {
            return
        }
        processMsgBody(msg, D, tag)
    }

    fun w(tag: String, msg: String) {
        if (!open) {
            return
        }
        processMsgBody(msg, W, tag)
    }

    fun e(tag: String, msg: String) {
        if (!open) {
            return
        }
        processMsgBody(msg, E, tag)
    }

    fun printLog(flag: Int, tag: String, msg: String = processTagAndHead()) {
        Log.println(flag, tag, LEFT_BORDER + msg)
    }

    fun printBottom(flag: Int, tag: String) {
        Log.println(flag, tag, BOTTOM_BORDER)
    }

    fun printTop(flag: Int, tag: String) {
        Log.println(flag, tag, TOP_BORDER)
    }

    fun closeLog() {
        this.open = false
    }


}
複製程式碼

相關文章