Search code examples
kotlinloggingslf4jkotlin-logging

How do I get kotlin-logging (MicroUtils) to print to subclass name instead of abstract class name?


I'm using kotlin-logging (https://github.com/MicroUtils/kotlin-logging), I want my logger to print to subclass name instead of abstract class name. Example I have these class

// in A.kt file:

import mu.KotlinLogging

private val logger = KotlinLogging.logger {}

abstract class A<T> {
    fun someMethod(item: T?) {
        logger.info("testing")
    }
}



fun main() {
    val b: A<String> = B()
    b.someMethod("123")
}




// in B.kt file

import mu.KotlinLogging

private val logger = KotlinLogging.logger {}

class B : A<String>() {
}

It prints: [main] INFO A - testing

But I want it to print: [main] INFO B - testing (where B is the subclass name)


Solution

  • You may want to send the logger to the abstract class.

    // in A.kt file:
    
    import mu.KotlinLogging
    
    abstract class A<T>(private val logger: KLogger) {
        fun someMethod(item: T?) {
            logger.info("testing")
        }
    }
    
    
    
    fun main() {
        val b: A<String> = B()
        b.someMethod("123")
    }
    
    
    
    
    // in B.kt file
    
    import mu.KotlinLogging
    
    private val logger = KotlinLogging.logger {}
    
    class B : A<String>(logger) {
    }
    

    Result: [main] INFO B - testing