首页 > 解决方案 > 如何让 kotlin-logging (MicroUtils) 打印到子类名而不是抽象类名?

问题描述

我正在使用 kotlin-logging ( https://github.com/MicroUtils/kotlin-logging ),我希望我的记录器打印到子类名称而不是抽象类名称。示例我有这些课程

// 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>() {
}

它打印:[main] INFO A - testing

但我希望它打印:[main] INFO B - testing (其中 B 是子类名称)

标签: kotlinloggingslf4jkotlin-logging

解决方案


您可能希望将记录器发送到抽象类。

// 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) {
}

结果: [main] INFO B - testing


推荐阅读