Currently executing method name and line number

Is there a way to get the currently executing method and line number to Logcat in Kotlin. I’m trying to use Log.d() function. I can use localClassName to get the current class but function name and line number is not possible. Also I don’t need the full stack trace.

4 Likes

No, there is no API in Kotlin to get the current line number.

I tried to solve that with this, maybe something still needs to be improved.

/**
 * Log.i(className,"methodName() Line : this")
 */
fun <T : Any> T.info(): T {
    val res = this
    Throwable().stackTrace[1].apply {
        Log.i(generateTag(), generateMessage(res))
    }
    return this
}

/**
 * Log.i(className,"methodName() Line : msg")
 */
fun <T : Any> T.info(msg: () -> Any): T {
    Throwable().stackTrace[1].apply {
        Log.i(generateTag(), generateMessage(msg()))
    }
    return this
}

fun StackTraceElement.generateTag()
        = className.substringAfterLast(".")

fun StackTraceElement.generateMessage(msg: Any = "")
        = "$methodName() Line $lineNumber: $msg"
2 Likes