Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Dependency Injection

I want to inject a Log4j Logger (or in case of generality any class) into all my classes that has a log property:

def log

This is done in Grails automatically. I want to have the same feature in ordinary groovy apps, lets say for all groovy files under src. The speciality with Log4j is, that the logger needs to know the class which to log. (Logger.getLogger(Class clazz))

How can I achieve this?

like image 897
matcauthon Avatar asked Jul 04 '12 10:07

matcauthon


2 Answers

Have you seen the @Log annotation added in Groovy 1.8?

like image 128
tim_yates Avatar answered Sep 21 '22 10:09

tim_yates


Groovy provides native support for this using the @Log4j annotation on the class. This creates a log field pointing to the Log4J Logger with the same name as the class in question, i.e.:

package com.example
import groovy.util.logging.Log4j

@Log4j
public class LogExample {
}

is the equivalent of

package com.example
public class LogExample {
  private static final Logger log = Logger.getLogger(LogExample.class)
}
like image 30
Ian Roberts Avatar answered Sep 25 '22 10:09

Ian Roberts