2

Is there a way to do the following without having to manually define the logging methods e.g. def error:

object FooBar {
  lazy val log = LoggerFactory.getLogger("AndroidProxy")
  def error(msg: String) = log.error(msg)


  def my_method(): Unit = {
    error("This is an error!")
  }
}
Hamy
  • 20,662
  • 15
  • 74
  • 102

2 Answers2

5

replace def error with

import log.error
0__
  • 66,707
  • 21
  • 171
  • 266
  • Awesome!! Is there any shorthand for importing log,error,info all at once? I can do `import log._` -- I'm not experienced enough to know if that has nasty side effects – Hamy Feb 16 '13 at 01:18
  • 2
    `import log._` or `import log.{info, trace, error}`. Lastly, renaming: `import log.{info => inf, trace => trc, error => err}` (for the three-letter-obsessed...). – Randall Schulz Feb 16 '13 at 02:15
  • Thanks Randall! If you're interested, I have a minor follow up question [here](http://stackoverflow.com/questions/14906830/import-specific-method-signature-in-scala) – Hamy Feb 16 '13 at 04:13
1

If you want to log in many classes and not rewrite the logging method every time, you can create a trait

trait Logging {
    lazy val logger = LoggerFactory.getLogger(getClass())

    def error(msg: => String) = log.error(msg)
}

Then in the classes where you need logging you do...

class MyClass extend Logging {
    def method() {
        //do stuff
        error("oups!")
    }
}

It is usually a good idea to pass the msg parameter by name (using :=> String) so that the string argument is evaluated only if used.

Also, notice that getClass is now the name of the logger. Which is helpful because now the name of the logger is the name of the class extending the Logging trait and not a hardcoded name.

Felix Trepanier
  • 346
  • 1
  • 5