Kotlin Logs Kotlin.jvm.internal.ClassReference as Log Prefix in Server Logs


#1

Hi,

I am using Apache Logging library (org.apache.logging.log4j) to log various things as part of my server stack.
Using code block similar to below generates following type of Log statements in the server logs… Why is the log prefix NOT that of Kotlin class through which instance of Log4j is created? This happens only when I log statements from within lambda functions like also.

class KotlinClass {

    companion object {
        val LOG = org.apache.logging.log4j.LogManager.getLogger(KotlinClass::class)
    }

...
...

fun doSomething() {

    LOG.info("Inside doSomething() method")
    val isValid = getValid().also {
                                            LOG.info("Obtained valid result $it")
                                       }
}

Server generated LOG:

...
TIMESTAMP.. com.abcd.efgh.KotlinClass: Inside doSomething() method
TIMESTAMP.. Kotlin.jvm.internal.ClassReference: Obtained valid result false
...

Any idea on what can be done to log ‘Class Name’ as prefix irrespective of where the log is being generated?


#2

I am not really sure why that happens, but this is what I use:

Filename: HelloWorld.kt

import java.util.*

private val LOG: org.apache.logging.log4j.Logger = org.apache.logging.log4j.LogManager.getLogger()

class Test {
    fun doSomething() {
        LOG.info("Inside doSomething() method")
        Random().nextInt().also { LOG.info("Generated random integer: $it") }
    }
}

fun main(args: Array<String>) {
    LOG.info("Hello world!")
    Test().doSomething()
}

And the output is this:

2018-05-17 22:47:40,820 I [main] [HelloWorldKt] Hello world!
2018-05-17 22:47:40,823 I [main] [HelloWorldKt] Inside doSomething() method
2018-05-17 22:47:40,825 I [main] [HelloWorldKt] Generated random integer: 405623303

This way, instead of logging the calss name it will log the filename.


#3

The type of expression KotlinClass::class is KClass, not Class. So method you called was LogManager.getLogger(Object), which calls .getClass() on it argument. You should use expresion KotlinClass::class.java.