Reputation: 247
In Java I would write logger.getLogger(NameOfClass.class)
. How to write the same in Scala?
Upvotes: 3
Views: 651
Reputation: 8463
Don't forget to define the logger on the singleton companion object:
object MyClass {
// Commons logging
private val clLogger = LogFactory.getLog(getClass())
// java.util.logging
private val juLogger = Logger.getLogger(getClass().toString)
}
class MyClass {
import MyClass._
...
}
The reason one should do this is that if you place the field on the class
it's an instance field which goes back to the logger factory on every new
instance of an object of that class. This can be unnecessary/unacceptable performance for some classes.
Scala's separation of the class (static) fields and instance fields, in this case, makes this much more arduous than would be done with Java. One of those cases where Scala doesn't have all the advantages:
class MyClass {
// Commons logging
private static final Log clLogger = LogFactory.getLog(MyClass.class)
// java.util.logging
private static final Logger juLogger = Logger.getLogger(MyClass.class.toString)
...
}
Upvotes: 1
Reputation: 13959
You could try:
logger.getLogger(getClass())
or:
logger.getLogger(classOf[NameOfClass])
As a side note, ScalaLogging provides a nice and easy way to use a logger with the class name but without all of the boilerplate like normal java. You get a logger in your class setup properly and all you have to do is extend a trait Logging
:
class MyClass extends Logging {
logger.debug("This is very convenient ;-)")
}
Upvotes: 9