Logging with log4j-An Efficient Way to Log Java Applications, Page 3
The log4j can be configured both programmatically and externally using special configuration files. External configuration is most preferred, because to take effect it doesn't require change in application code, recompilation, or redeployment. Configuration files can be XML files or Java property files that can be created and edited using any text editor or XML editor, respectively.
The simplest configuration file will contain following specifications that can be modified, both programmatically and externally, to suit specific logging requirements.
- The priority level and name of appender assigned to root logger.
- The appender's type (for example ConsoleAppender or FileAppender, and so forth).
- The layout assigned to the appender (as SimpleLayout or PatternLayout and the like).
Listing 4 gives an example of configuration file config-simple.properties (in Java property format).
Listing 4: A simple configuration file config-simple.properties in Java property format.
# The root logger is assigned priority level DEBUG and an appender # named myAppender. log4j.rootLogger=debug, myAppender # The appender's type specified as FileAppender, i.e. log output # written to a file. log4j.appender.myAppender=org.apache.log4j.FileAppender # The appender is assigned a layout SimpleLayout. # SimpleLayout will include only priority level of the log # statement and the log statement itself in log output. log4j.appender.myAppender.layout=org.apache.log4j.SimpleLayout
Listing 5 shows an XML configuration file with similar specifications.
Listing 5: Configuration file log4j.xml in XML format.
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="myAppender" class="org.apache.log4j.FileAppender"> <layout class="org.apache.log4j.SimpleLayout"/> </appender> <root> <priority value="debug" /> <appender-ref ref="myAppender"/> </root> </log4j:configuration>
To use a log4j configuration file, it should be loaded using following code, preferably inserted in startup class of the application.
import org.apache.log4j.PropertyConfigurator; ... PropertyConfigurator.configure("path/to/configuration_file");
Advantages and Shortcomings
The advantages of using log4j are listed below:
- The log4j printing methods used for logging can always remain in application code because they do not incur heavy process overhead for the application and assist in ongoing debugging and monitoring of application code, thus proving useful in the long term.
- Log4j organizes the log output in separate categories by the name of generating loggers that in turn are same as the names of the classes they log. This approach makes pinpointing the source of an error easy.
- Log4j facilitates external configuration at runtime; this makes the management and modification of log statements very simple and convenient as compared to performing the same tasks manually.
- Log4j assigns priority levels to loggers and log requests. This approach helps weed out unnecessary log output and allows only important log statements to be logged.
The shortcomings of log4j are listed below:
- Appender additivity may result in the log requests being unnecessarily sent to many appenders and useless repetition of log output at an appeneder. Appender additivity is countered by preventing a logger from inheriting appenders from its ancestors by setting the additivity flag to false.
- When configuration files are being reloaded after configuration at runtime, a small number of log outputs may be lost in the short time between the closing and reopening of appenders. In this case, Log4j will report an error to the stderr output stream, informing that it was unable send the log outputs to the appender(s) concerned. But the possibility of such a situation is minute. Also, this can be easily patched up by setting a higher priority level for loggers.
Although log4j has received competition from new a logging API integrated into JSDK 1.4, log4j's strengths of being a mature, feature-ric, and efficient logging API framework, and wide usage for a long time are bound to hold against any competition. Also, compatibility with JSDK 1.4's logging API for easy to-and-fro migration, possibility for further improvements in this API, and new features to suit growing needs will surely make log4j's use continue for a long time to come.
The log4j API provides a means for inserting useful and manageable log statements in the application code, assigning priority levels to them to make sure only relevant log statements get logged, and specifying formats the log statements are written in and managing log statements externally with no need of changing containing application's code, recompile, or redeployment.
- Log4j is freely available to download from The Apache Jakarta Project Web site.
- A comprehensive tutorial "Short introduction to log4j" for understanding log4j is available at log4j's homepage.
- Complete javadoc documentation of the log4j API is available at http://jakarta.apache.org/log4j/docs/api/index.html.
- Documentation for log4j PatternLayout is useful to learn how to format log output using different patterns.
- A useful article, "Build Flexible Logs With log4j," contains examples of log4j property files along with tips and tricks at onjava.com.
- This userWorks article "Instant logging: Harness the power of log4j with Jabber" explores logging solutions through instant messaging (IM) using log4j.
In a log4j package hierarchy, a logger's parent (and nearest existing ancestor) is the logger whose name immediately proceeds its own in standard package notation. For example: For a logger com.foo.sampleapp.MyClass, com.foo.sampleapp is its parent and com.foo, com and root logger are its ancestors if they actually exist.
To create a logger instance, existence of its parent/ancestor is not necessary; unlike with standard class hierarchy. A logger implicitly inherits from its nearest existing ancestor, if its parent doesn't exist. The root logger is the top-most ancestor that always exists.
About the Author
Mugdha Chauhan (formerly Mugdha Vairagade) is a senior IT consultant and author. An Open Source supporter, she frequently writes articles and tutorials on useful emerging Open Source projects. Major tech portals including developer.com, IBM developerWorks, CNET Networks, Slashdot, and many eZines regularly publish her work. Her expertise and interests include Java, Linux, XML, wireless application development, and Open Source.