Kotlin extension logarithm function with logback (slf4j)

I created an extension function for logging:

import org.slf4j.LoggerFactory

fun Any.log(msg: String) {
    LoggerFactory.getLogger(javaClass.name).debug(msg)
}

But I'm not sure if this will be init anytime it is called or not, because the method LoggerFactory.getLoggercalls getILoggerFactory.

Mb someone has already done something similar and can assure me that he will not have memory leaks :)?

I am currently using the old fashion approach (declaring a registrar field in a class):

companion object {
    private val logger = LoggerFactory.getLogger(LoggerTest::class.java.name)
}

but a simple test unitlooks like this:

@Test
fun testLogger() {
    val start = System.currentTimeMillis()
    for (i in 0..999) {
        log("i=" + i)
    }
    val end = System.currentTimeMillis()
    val time = end - start
    println("*** TIME=" + time.toDouble() / 1000 + " sec")
}

shows the same result as for the old fashion:

@Test
fun testLogger() {
    val start = System.currentTimeMillis()
    for (i in 0..999) {
        logger.debug("i=" + i)
    }
    val end = System.currentTimeMillis()
    val time = end - start
    println("*** TIME=" + time.toDouble() / 1000 + " sec")
}

companion object {
    private val logger = LoggerFactory.getLogger(LoggerTest::class.java.name)
}

~ *** TIME=0.02 sec

I use:

org.slf4j - 1.7.25
ch.qos.logback - 1.2.3
+4
source share
2 answers

For logging, I could recommend another solution.

First add the ILogging interface and the LoggingImpl class:

interface ILogging {
    val log: Logger
}

class LoggingImp(loggerImpl: Logger) : ILogging {
    override val log: Logger = loggerImpl

    companion object {
        operator inline fun <reified T> invoke(): LoggingImp {
            return LoggingImp(LoggerFactory.getLogger(T::class.java))
        }
    }
}

, Kotlin:

class TestClass : ILogging by LoggingImp<TestClass>() {
    fun test() {
        log.info("test")
    }
}

. :

fun main(args: Array<String>) {
    val testClass = TestClass()

    testClass.test()
}

, .

+3

.

interface ILogger {

  @get:JsonIgnore
  val logger: Logger
      get() = LoggerFactory.getLogger(this)
}

:

class TestClass : ILogging {
  fun test() {
      logger.info("test")
  }
}
-1

Source: https://habr.com/ru/post/1688134/


All Articles