Menu Search Sign up

Log4j 2 Concepts

Log4j has three main components:

  • loggers: Responsible for capturing logging information.
  • appenders : Responsible for publishing logging information to various preferred destinations.
  • layouts: Responsible to format logging information in different styles

In addition, in log4j, the org.apache.logging.log4j.LogManager object manages the overall logging framework. It is responsible for reading the initial configuration parameters from a system-wide configuration file or a configuration class.

The org.apache.log4j.Level class provides following levels but you can also define your custom levels by sub-classing the Level class.

LevelDescription
ALL All levels including custom levels.
DEBUG Designates fine-grained informational events that are most useful to debug an application.
ERROR Designates error events that might still allow the application to continue running.
FATAL Designates very severe error events that will presumably lead the application to abort.
INFO Designates informational messages that highlight the progress of the application at coarse-grained level.
OFF The highest possible rank and is intended to turn off logging.
TRACE Designates finer-grained informational events than the DEBUG.
WARN Designates potentially harmful situations.

A log request of level p in a logger with level q, is enabled if p >= q. This rule is at the heart of log4j. It assumes that levels are ordered. For the standard levels, we have ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF.

When you invoke logging from your Java program, you will need to specify the level of logging so that the log4j framework can determine if it will be enabled (ie, written to the appropriate logging destinations). For example, if in your Java program, you have a line of code to log a message at INFO level, and you have configured your log4j configuration file at the WARN level, then this INFO level message will not be written to the destinations. If, however, if you change  your configuration to be at the DEBUG leve, then this INFO level message will be written to the detinations.

Usually, you interact with log4j 2 from within your program as well as from a configuration file. From within your Java program:

  • You create a named logger
  • You log different messages at different levels (debug, info, warn, etc.) based on your programming needs

From a configuration file (can be either an XML file or a simple name=value properties file):

  • You specify how the logs at different levels from different loggers (or from all loggers) should be formatted via layout configuration
  • You specify where the logs at different levels from different loggers (or from all loggers) should be published via appender configuration