Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added @Log documentation from Groovy 1.8 release notes

...

Code Block
$ groovy -e "println 'hi'"
13.09.2005 14:33:05 script_from_command_line run()
FEINER: called from MetaClass.invokeMethod
13.09.2005 14:33:05 script_from_command_line println('hi')
FEINER: called from MetaClass.invokeMethod
hi

@Log

You can annotate your classes with the @Log transformation to automatically inject a logger in your Groovy classes, under the log property. Four kind of loggers are actually available:

  • @Log for java.util.logging
  • @Commons for Commons-Logging
  • @Log4j for Log4J
  • @Slf4j for SLF4J

Here's a sample usage of the @Log transformation:

Code Block
import groovy.util.logging.*

@Log
class Car {
    Car() {
        log.info 'Car constructed'
    }
}

def c = new Car()

You can change the name of the logger by specifying a different name, for instance with @Log('myLoggerName').

Another particularity of these logger AST transformations is that they take care of wrapping and safe-guarding logger calls with the usual isSomeLevelEnabled() calls. So when you write log.info 'Car constructed', the generated code is actually equivalent to:

Code Block
if (log.isLoggable(Level.INFO)) {
    log.info 'Car constructed'
}

See Also