Log的kotlin简单封装

该博客介绍了一个Kotlin编写的辅助函数,用于在调试模式下打印带有堆栈跟踪的日志。函数`log()`接收字符串参数,并在调试模式下通过`Log.d()`方法输出,同时使用`getAutoJumpLogInfo()`获取并处理堆栈信息,以便提供更详细的日志上下文。此外,`isDebug()`函数检查应用是否处于调试状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

kotlin file

1.kotlin文件

fun log(content: String) = run {
    if (isDebug()) {
        getAutoJumpLogInfo().apply {
            Log.d(this[1], "${this[0]}=====$content")
        }
    }
}

private fun getAutoJumpLogInfo(): Array<String> {
    val contents = arrayOf("", "")
    val stackTrace = Thread.currentThread().stackTrace
    return if (stackTrace.size < 6) {
        Log.e("LogKtx", "Stack is too shallow!!!")
        contents
    } else {
        fun splicing(index: Int = 4, methodIndex: Int = 5) {
            stackTrace[methodIndex].methodName.toString().let {
                stackTrace[index].toString().substringAfter(it).apply {
                    contents[0] = this
                    contents[1] = this.substringBefore(".").substringAfter("(")
                }
            }
        }
        stackTrace[5].methodName.toString().let {
            when {
                stackTrace[4].toString().contains(it) -> splicing()
                stackTrace[4].toString().contains(stackTrace[4].methodName.toString()) -> splicing(
                    methodIndex = 4
                )
                else -> splicing(5)
            }
        }
        contents
    }
}

private fun isDebug(): Boolean {
    return try {
        val info = App.get().applicationInfo
        (info.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0
    } catch (e: Exception) {
        false
    }
}

2.调用

log("variable$variable")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值