Log4j 2 API

Overview

The Log4Jj 2 API provides the interface that applications should code to and provides the adapter components required for implementers to create a logging implementation. Although Log4j 2 is broken up between an API and an implementation, the primary purpose of doing so was not to allow multiple implementations, although that is certainly possible, but to clearly define what classes and methods are safe to use in "normal" application code.

Hello World!

No introduction would be complete without the customary Hello, World example. Here is ours. First, a Logger with the name "HelloWorld" is obtained from the LogManager. Next, the logger is used to write the "Hello, World!" message, however the message will be written only if the Logger is configured to allow informational messages.

    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;

    public class HelloWorld {
        private static Logger logger = LogManager.getLogger("HelloWorld");
        public static void main(String[] args) {
            logger.info("Hello, World!");
        }
    }

The output from the call to logger.info() will vary significantly depending on the configuration used. See the Configuration section for more details.

Parameter Substitution

Frequently the purpose of logging is to provide information about what is happening in the system, which requires including information about the objects being manipulated. In Log4j 1.x this could be accomplished by doing:

    if (logger.isDebugEnabled()) {
        logger.debug("Logging in user " + user.getName() + " with id " + user.getId());
    }

Doing this repeatedly has the effect of making the code feel like it is more about logging than the actual task at hand. In addition, it results in the logging level being checked twice; once on the call to isDebugEnabled and once on the debug method. A better alternative would be:

    logger.debug("Logging in user {} with id {}", user.getName(), user.getId());

With the code above the logging level will only be checked once and the String construction will only occur when debug logging is enabled.