19

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 ?

3 Answers 3

50

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' } 
Sign up to request clarification or add additional context in comments.

6 Comments

Cannot work: this is not available at the time of initializing the static field
It does work, because in Groovy this in a static context refers to the Class object. Obviously this is a difference between Java and Groovy. Try it out if you don't believe me :)
I would assume the package would be org.slf4j.LoggerFactory, is this correct?
No, that's the log4J LogFactory
For completeness and correctness, we need to add the 'import' statement and '@Log4J' is actually '@Log4j'. I can confirm that it works in a class in /src/groovy with Grails 2.2.2: import groovy.util.logging.Log4j @Log4j class MiscUtils {...log.info "m: ${m}"...}
|
11

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

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

or

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

1 Comment

This is how i solved it ATM, but stil means that my class is tied to the logging system even when the logging beans of the entire application get changed.
0

Using the standard Log4j's new Logger(getClass()) worked, but logged 'java.lang.Class' for me (using Grails 1.2.1). This problem went away with the Sublog plugin and @WithLog. See http://www.grails.org/plugin/sublog. This plugin also does not make Trace become Debug and Fatal Error...!

2 Comments

Hi Olivier, this question is kind of stale by now, since it was meant for grails 1.0.4.
This is not mentioned in the question, though. My answer still stands! :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.