Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

Steven has posted 36 posts at DZone. View Full User Profile

Groovy and Log4j

01.20.2008
Email
Views: 9964
  • submit to reddit

I'm sure you recognize this situation. You're happily coding away, run your code for the first time and see the dreaded Log4j message on your console:

log4j:WARN No appenders could be found for logger (some.framework.Class).
log4j:WARN Please initialize the log4j system properly.

Desperation strikes. You can ignore it but if you want to see log messages you have to find an example of a Log4j configuration file, maybe modify it and put it in the right location so it can be found on the class path. You easily loose 15 minutes of your time if not more and with it your mojo.

No more. Next time this happens add these three lines to you Groovy code and you're cooking with gas:

import org.apache.log4j.*

BasicConfigurator.configure()
LogManager.rootLogger.level = Level.INFO

This will configure a ConsoleAppender and set the root logger to a convenient INFO level.

You can further tweak any Loggers you want. For example, to turn on the logging of Hibernate SQL statements add this line:

LogManager.getLogger("org.hibernate.SQL").level = Level.DEBUG

To prevent log messages bubbling up to parent loggers (and thus logged twice of more) set the additivity property for any Logger to false:

LogManager.getLogger("org.hibernate.SQL").additivity = false

Happy coding!

Published at DZone with permission of its author, Steven Devijver.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Stefan Lecho replied on Mon, 2008/01/28 - 5:38am

We are currently using Log4j in our Java projects. These projects are deployed in Tomcat and/or JBoss and require a "normal" log4j.xml file.

Is there a way to generate based on the Groovy code a "normal" log4j.xml file that can be deployed in Tomcat and/or JBoss ?

James Childers replied on Mon, 2008/02/04 - 5:17pm

Ack.

Ok, I just tried this, and while it works it is certainly not ideal. (a) There are four lines of boilerplate code that must be introduced into every class, and (b) log4j.xml is ignored. This latter is a big one, because changing logging levels requires rebuilding and restarting. There may be some classloader-fu that could be done to prevent this necessity, but it would still be annoying even then because most systems use log4j.xml extensively; moving this logic into the class itself is definitely a step backwards.

Blech. For my part I curse ACL. BUT that's neither here nor there.

 

  

  

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.