What Is log4j?
Log4j is an OpenSource logging API for Java. This logging API, currently in version 1.2.8, became so popular that it has been ported to other languages such as C, C++, Python, and even C# to provide logging framework for these languages.
What Can log4j Do?
- Log4j handles inserting log statements in application code and managing them externally without touching application code, by using external configuration files.
- Log4j categorizes log statements according to user-specified criteria and assigns different priority levels to these log statements. These priority levels decide which log statements are important enough to be logged to the log repository.
- Log4j lets users choose from several destinations for log statements, such as console, file, database, SMTP servers, GUI components etc.; with option of assigning different destinations to different categories of log statements. These log destinations can be changed anytime by simply changing log4j configuration files.
- Log4j also facilitates creation of customized formats for log output and provides default formats in which log statements will be written to log destination.
How Does log4j Work?
Logically, log4j can be viewed as being comprised of three main components: logger, appender, andlayout namely. The functionalities of each of these components are accessible through Java classes of the same name. Users can extend these basic classes to create their own loggers, appenders, and layouts.
Logger
The component logger accepts or enables log requests generated by log statements (or printing methods) during application execution and sends their output to appropriate destination, i.e.appender(s), specified by user.
The logger component is accessible through the Logger class of the log4j API. This class provides a static method Logger.getLogger(name) that either retrieves an existing logger object by the given name, or creates a new logger of given name if none exists. This logger object is then used to set properties of logger component and invoke printing methods debug(), info(), warn(), error(), fatal(), andlog(). These methods generate log requests during application execution. These methods and their respective usage are discussed in following section.
Each class in the Java application being logged can have an individual logger assigned to it or share a common logger with other classes. One can create any number of loggers for the application to suit specific logging needs. It is a common practice to create one logger for each class, with a name same as the fully-qualified class name. This practice helps organize log outputs in groups by the classes they originate from, and identify origin of log output, which is useful for debugging.
Log4j provides a default root logger that all user-defined loggers inherit from. Root logger is at the top of the logger hierarchy; in other words, root logger is either parent or ancestor of all logger objects created. If an application class doesn't have a logger assigned to it, it can still be logged using the root logger.
For example: A class MyClass in com.foo.sampleapp application package can have a logger named com.foo.sampleapp.MyClass instantiated in it by using theLogger.getLogger("com.foo.sampleapp.MyClass") method. This logger will implicitly inherit from its nearest existing ancestor (maybe com.foo.sampleapp or com.foo or ...; or root logger if none exists), follow the same parent-child relationship as the class-subclass they log and have same package hierarchy as these classes.
Priority levels of log statements
Loggers can be assigned different levels of priorities. These priority levels decide which log statement is going to be logged. There are five different priority levels: DEBUG, INFO, WARN, ERROR, andFATAL; in ascending order of priority. As we can see, log4j has corresponding printing methodsfor each of these priority levels. These printing methods are used to generate log requests of corresponding priority level for log statements. For example: mylogger.info("logstatement-1"); generates log request of priority level INFO for logstatement-1.
The root logger is assigned the default priority level DEBUG. All loggers inherit priority level from their parent or nearest existing ancestor logger, which is in effect until they are assigned another priority level. A logger object can be assigned a priority level either programmatically by invoking its methodsetLevel(Level.x) where x can be any of the five priority levels, or through external configuration files. The latter is the most preferred way to do so.
After assigning a priority level to a logger, it will enable only those log requests with a priority level equal to or greater than its own. This technique helps prevent log statements of lesser importance from being logged. This concept is the core of log4j functionality.
Listing 1: Example of priority level of logger and log requests.
/* Instantiate a logger named MyLogger */
Logger mylogger = Logger.getLogger("MyLogger");
...
/* Set logger priority level to INFO programmatically. Though
this is better done externally */
mylogger.setLevel(Level.INFO);
...
/* This log request is enabled and log statement logged,
since INFO = INFO */
mylogger.info("The values of parameters passed to do_something( )
are: " + a, b);
...
/* This log request is not enabled, since DEBUG < INFO */
mylogger.debug("Operation performed successfully");
...
/* this log request is enabled and log statement logged, since
ERROR > INFO*/
mylogger.error("Value of X is null");
Appender
Appender component is interface to the destination of log statements, a repository where the log statements are written/recorded. A logger object receives log request from log statements being executed, enables appropriate ones, and sends their output to the appender(s) assigned to it. The appender writes this output to repository associated with it. There are various appenders available; such as ConsoleAppender(for console), FileAppender (for file), JDBCAppender (for database), SMTPAppender (for SMTP server), SocketAppender (for remote server) and even Instant Messenger (for IMAppender).An appender is assigned to a logger using the addAppender( ) method of the Logger class, or through external configuration files. A logger can be assigned one or more appenders that can be different from appenders of another logger. This is useful for sending log outputs of different priority levels to different destinations for better monitoring. For example: All log outputs with levels less than FATAL and ERROR being sent to files, while all those with levels equal to ERROR and FATAL sent to console for faster detection.A logger also implicitly inherits appenders from its parents (and from ancestors, in that effect). Therefore, the log requests accepted by logger are sent to its own appenders along with that of all its ancestors. This phenomenon is known as appender additivity.Layout
The Layout component defines the format in which the log statements are written to the log destination by appender. Layout is used to specify the style and content of the log output to be recorded; such as inclusion/exclusion of date and time of log output, priority level, info about the logger, line numbers of application code from where log output originated, and so forth. This is accomplished by assigning a layout to the appender concerned.
Layout is an abstract class in log4j API; it can be extended to create user-defined layouts. Some readymade layouts are also available in a log4j package; they are PatternLayout, SimpleLayout, DateLayout,HTMLLayout, and XMLLayout.