Page tree
Skip to end of metadata
Go to start of metadata

The Log4j 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!

所有有关软件的介绍和使用都是从 Hello World 开始的,这里是我们的 Hello World 示例程序。首先,日志从 LogManager 中获得日志名 Hello World, 然后,日志使用被使用,输出了 "Hello, World!" 这条信息。


在下面的示例程序中,日志的级别被定义为 info,如果你定义日志输出的级别为 ERROR 的话,这条日志是不会被输出的。

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class HelloWorld {
    private static final Logger logger = LogManager.getLogger("HelloWorld");
    public static void main(String[] args) {"Hello, World!");

输出日志消息的方法 与日志的配置是密切相关的,请参考 Log4j 2 配置 章节中有关的内容。


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 birthday " + user.getBirthdayCalendar());

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 birthday {}", user.getName(), user.getBirthdayCalendar());

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

  • No labels