android_封装log.d()等日志调试工具(支持自动打印调用者的函数名)

借助IDEA

参看live template 配置:
https://blog.csdn.net/xuchaoxin1375/article/details/117840911

不借助IDE

code:

对原生log系列的函数进行封装,可以更加灵活的定义日志调试工具
这里提供一个可以自动打印调用者函数名的版本
为其中的d()函数做了支持,其他函数类似,关键是利用了函数调用栈

package com.zjgsu.cxxu.memowithmindmap

import android.util.Log

/**
 * the LogUtil singleton class will convenient the debug and toggle the mode whether to print
 * logs in the console in all kinds of levels
 * it mainly sealed the original log utils to the LogUtil*/

object Lg {


    private const val VERBOSE = 1

    private const val DEBUG = 2

    private const val INFO = 3

    private const val WARN = 4

    private const val ERROR = 5

    private var level = DEBUG

    val stackTrace = Thread.currentThread().stackTrace

    /*getThreadStackTrace-> getStackTrace-> onCreate(调用栈(越早越深)*/
//        val methodName=stackTrace[0].methodName+" "
//        val methodName1=stackTrace[1].methodName+" "
    fun getLgInvokerName():String {
        /*根据实际情况将4调整为3或其他数值*/
        return stackTrace[4].methodName + "():"
    }


    @JvmStatic
    fun v(tag: String, msg: String) {
        if (level <= VERBOSE) {
           val msg= getLgInvokerName()+msg
            Log.v(tag, msg)
        }
    }

    @JvmStatic
    fun d(tag: String, msg: String) {
//        val stackTrace = Thread.currentThread().stackTrace
//        /*getThreadStackTrace-> getStackTrace-> onCreate(调用栈(越早越深)*/
        val methodName=stackTrace[0].methodName+" "
        val methodName1=stackTrace[1].methodName+" "
//        val lgDInvoker = stackTrace[3].methodName + " "
        val msg= getLgInvokerName()+msg
        if (level <= DEBUG) {
            Log.d(tag,  msg)
        }
    }

    @JvmStatic
    fun i(tag: String, msg: String) {
        if (level <= INFO) {
            Log.i(tag, msg)
        }
    }

    @JvmStatic
    fun w(tag: String, msg: String) {
        if (level <= WARN) {
            Log.w(tag, msg)
        }
    }

    @JvmStatic
    fun e(tag: String, msg: String) {
        if (level <= ERROR) {
            Log.e(tag, msg)
        }
    }

}

posted @ 2023-07-20 11:55  xuchaoxin1375  阅读(10)  评论(0)    收藏  举报  来源