What is the best way to define log TAG constant in Kotlin?

后端 未结 17 2112
暗喜
暗喜 2021-01-30 16:00

I\'m creating my first Kotlin classes in my Android application. Usually for logging purposes I have a constant with name TAG. What I would do in Java is:



        
17条回答
  •  无人及你
    2021-01-30 16:33

    AnkoLogger uses an interface to define the log tag.

    interface AnkoLogger {
                /**
                 * The logger tag used in extension functions for the [AnkoLogger].
                 * Note that the tag length should not be more than 23 symbols.
                 */
                val loggerTag: String
                    get() = getTag(javaClass)
            }
    private fun getTag(clazz: Class<*>): String {
            val tag = clazz.simpleName
            return if (tag.length <= 23) {
                tag
            } else {
                tag.substring(0, 23)
            }
        }
    inline fun AnkoLogger.info(message: () -> Any?) {
        val tag = loggerTag
        if (Log.isLoggable(tag, Log.INFO)) {
            Log.i(tag, message()?.toString() ?: "null")
        }
    }
    

    You can use it like this:

    class MyClass : AnkoLogger {
        fun someFun(){
           info("logging info")
        }
    }
    

    Maybe AnkoLogger can give you some ideas to implement a custom logging tool.

提交回复
热议问题