Over a million developers have joined DZone.

Groovy and Log4j

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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!

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}