About Dustin Marx

Easy and Consistent Log4j2 Logger Naming

In the post Portable Logger Names with Java 7 Method Handles, I wrote about using Java 7‘s method handles to name classes’ loggers. I stated in that post that advantages of that approach included consistency in logger naming and avoiding accidental copying and pasting of code that might lead to a different class’s name being used for the logger name. In this post, I look at how Log4j 2 provides an approach for achieving these same benefits.

Log4j 2 recognizes the prevalent approach to naming loggers based off of classes’ names. The “Logger Names” section of the “Log4j 2 API” page in the Log4j 2 Manual states, “In most cases, applications name their loggers by passing the current class’s name to LogManager.getLogger. Because this usage is so common, Log4j 2 provides that as the default when the logger name parameter is either omitted or is null.”

The following very simple Calculator class demonstrates this, creating a Logger with a parameter-less LogManager.getLogger() call. Because no parameter is passed to the getLogger() method, the logger will be named after the class in which the Logger is created. The Javadoc comment for method LogManager.getLogger() confirms this behavior: “Returns a Logger with the name of the calling class.”

With the Calculator class implemented as shown above, the class’s logger’s name, available by call to Logger.getName() as demonstrated in the Calculator method getLoggerName(), is “dustin.examples.log4j.Calculator”. Although not shown here, a Logger retrieved with parameter-less LogManager.getFormatterLogger() will also use “the fully qualified name of the calling Class as the Logger name.”

Conclusion

The Log4j 2 approach discussed and demonstrated in this post for naming loggers is easy to use and makes it easy to have consistent and correct logger names, assuming that the chosen logger naming scheme is to use the fully qualified package and class name. This approach is briefer and arguably even more readable than the method handles approach to naming loggers, but this approach is specific to Log4j 2 while the method handles approach can be used with multiple logging frameworks and libraries.

Join Us

With 1,240,600 monthly unique visitors and over 500 authors we are placed among the top Java related sites around. Constantly being on the lookout for partners; we encourage you to join us. So If you have a blog with unique and interesting content then you should check out our JCG partners program. You can also be a guest writer for Java Code Geeks and hone your writing skills!

Disclaimer

All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners. Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries. Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.