开源框架JetpackMvvm中日志工具类 稍做修改 分享(之前整理了Timber 淘汰了)
1.在项目工具类型module中创建"LogExt.kt"代码如下
import android.util.Log
/**
* desc:日志打印工具
*/
private var TAG = "data_sense_log"
internal fun String?.setLogTag() {
this?.let {
TAG = it
}
}
//是否显示日志 默认打开
private var LogDisplayConfig = true
//设置日志显示开关
internal fun Boolean.setLogConfig() {
this.let {
LogDisplayConfig = it
}
}
private enum class LEVEL {
V, D, I, W, E
}
fun String.logV(tag: String = TAG) = log(LEVEL.V, tag, this)
fun String.logD(tag: String = TAG) = log(LEVEL.D, tag, this)
fun String.logI(tag: String = TAG) = log(LEVEL.I, tag, this)
fun String.logW(tag: String = TAG) = log(LEVEL.W, tag, this)
fun String.logE(tag: String = TAG) = log(LEVEL.E, tag, this)
/**
* log
*
* @param level
* @param tag
* @param message
*/
private fun log(level: LEVEL, tag: String, message: String) {
if (!LogDisplayConfig) return
when (level) {
LEVEL.V -> Log.v(tag, message)
LEVEL.D -> Log.d(tag, message)
LEVEL.I -> Log.i(tag, message)
LEVEL.W -> Log.w(tag, message)
LEVEL.E -> Log.e(tag, message)
}
}
在工具module中提供app调用的接口(ModuleConfig.kt)
fun Application.initLogConfig(logTag: String?,logSta :Boolean = true) {
logTag.setLogTag()
logSta.setLogConfig()
}
application设置
override fun onCreate() {
super.onCreate()
//根据BuildConfig设置是否显示日志信息
initLogConfig("my_app", BuildConfig.DEBUG)
}
"this is log info".logD()