Idiomatic way of logging in Kotlin

后端 未结 16 1453
情歌与酒
情歌与酒 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:47

    First, you can add extension functions for logger creation.

    inline fun  getLogger() = LoggerFactory.getLogger(T::class.java)
    fun  T.getLogger() = LoggerFactory.getLogger(javaClass)
    

    Then you will be able to create a logger using the following code.

    private val logger1 = getLogger()
    private val logger2 = getLogger()
    

    Second, you can define an interface that provides a logger and its mixin implementation.

    interface LoggerAware {
      val logger: Logger
    }
    
    class LoggerAwareMixin(containerClass: Class<*>) : LoggerAware {
      override val logger: Logger = LoggerFactory.getLogger(containerClass)
    }
    
    inline fun  loggerAware() = LoggerAwareMixin(T::class.java)
    

    This interface can be used in the following way.

    class SomeClass : LoggerAware by loggerAware() {
      // Now you can use a logger here.
    }
    

提交回复
热议问题