Idiomatic way of logging in Kotlin

后端 未结 16 1467
情歌与酒
情歌与酒 2020-12-07 07:34

Kotlin doesn\'t have the same notion of static fields as used in Java. In Java, the generally accepted way of doing logging is:

public class Foo {
    privat         


        
16条回答
  •  悲&欢浪女
    2020-12-07 07:51

    Have a look at the kotlin-logging library.
    It allows logging like that:

    private val logger = KotlinLogging.logger {}
    
    class Foo {
      logger.info{"wohoooo $wohoooo"}
    }
    

    Or like that:

    class FooWithLogging {
      companion object: KLogging()
      fun bar() {
        logger.info{"wohoooo $wohoooo"}
      }
    }
    

    I also wrote a blog post comparing it to AnkoLogger: Logging in Kotlin & Android: AnkoLogger vs kotlin-logging

    Disclaimer: I am the maintainer of that library.

    Edit: kotlin-logging now has multiplatform support: https://github.com/MicroUtils/kotlin-logging/wiki/Multiplatform-support

提交回复
热议问题