Inject log object in Grails class outside of grails-app

13,432

Solution 1

You'd add it just like a regular Java class:

Logger log = Logger.getLogger(getClass()) // log4j

or

Log log = LogFactory.getLog(getClass()) // commons logging

Solution 2

Grails 1.X

A more Groovy way to do the same thing is:

private static log = LogFactory.getLog(this)

This takes advantage of the fact that this in a static context refers to the Class object, so the line above can be copy-pasted from one class to another without modification.

Grails 2.X

Use the @Log4j annotation introduced in Groovy 1.8. This will add a log property

import groovy.util.logging.Log4j
@Log4j 
class MyClass {

  def doIt() {
    log.info 'hello'
  }
}

A nice benefit of using the annotation is that the logger automatically converts calls such as this:

log.info 'hello'

to:

if (log.isInfoEnabled() {
  log.info 'hello'
}
Share:
13,432
Azder
Author by

Azder

I code for living

Updated on June 05, 2022

Comments

  • Azder
    Azder almost 2 years

    I have a class in src/groovy in my grails project.

    How do i make a log field that gets injected with the correct logger for that class ?

    Is there a commons logging or just log4j in grails ?