Logger declaration


#1

Hi!

What is the recommended way in kotlin to declare a logger? I use this

class Foo {

  object constants {

  val logger = LoggerFactory.getLogger(javaClass<Foo>())

  }

  fun doSomething(name: String) {

  constants.logger.info("something: {}", name)

  }

}

The downside is of course to use the constants everywhere, very unusual…


#2

use special "class object" inplace of your inner object "constants"

class Foo {   class object {   val logger = LoggerFactory.getLogger(javaClass<Foo>())   }   fun doSomething(name: String) {   logger.info("something: {}", name)   } }

see http://confluence.jetbrains.com/display/Kotlin/Classes+and+Inheritance


#3

looks great, thank you!


#4

Just a quick update for the future reader, As with version 1.0.4,

class Foo {
  val logger = LoggerFactory.getLogger(Foo::class.java)

 fun doSomething(name: String) {
    logger.info("something: {}", name)

  }
}

#5

This creates one logger instance per class instance. If you want to use one logger instance per class, which is normally what you want and which the posts above do, you need to use a companion object.


#6

Yes, You’re right. Thanks.

companion object {
  val logger = LoggerFactory.getLogger(Foo::class.java)
}