Over a million developers have joined DZone.

Groovy and Log4j

DZone's Guide to

Groovy and Log4j

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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.*

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!

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}