developer.com
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
New
 
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!




Developer Jobs

Be a Commerce Partner














 


Developer News -
iPhone Users Just Want to Have Fun    August 26, 2008
Oops! I Fixed the Linux Kernel    August 22, 2008
Jim Zemlin: The New Center of Linux Gravity    August 21, 2008
Microsoft's Novell Investment Tops $340M    August 20, 2008
Free Tech Newsletter -

Logging with log4j—An Efficient Way to Log Java Applications
By Mugdha Chauhan

Go to page: 1  2  3  Next  

Log4j is an OpenSource logging API developed under the Jakarta Apache project. It provides a robust, reliable, fully configurable, easily extendible, and easy to implement framework for logging Java applications for debugging and monitoring purposes. Log4j allows developers to insert log statements in their code and configure them externally. This article covers the need for logging; a brief introduction to log4j; an explanation of its components and terminology, implementation, and configuration; its advantages and shortcomings; and how to use it to log Java applications.

The Need for Logging

Logging, or writing the state of a program at various stages of its execution to some repository such as a log file, is an age-old method used for debugging and monitoring applications. By inserting simple yet explanatory output statements (such as system.out.println() in the case of Java) in the application code that write to a simple text file, console, or any other repository, a reliable monitoring and debugging solution can be achieved. Although low-level, this is the mechanism to fall back upon when sophisticated debugging tools are either unavailable for any reason or useless; such as in a distributed application scenario.

Inserting log statements manually is tedious and time-consuming, not to mention managing them (such as modifying and updating) down the road due to various reasons such as ongoing upgrading and bug-fixing process for application code, and so forth. To ease this process, there is a useful, efficient, and easy-to-use utility available, called log4j API.

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?

  1. Log4j handles inserting log statements in application code and managing them externally without touching application code, by using external configuration files.
  2. 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.
  3. 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.
  4. 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, and layout 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(), and log(). 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 the Logger.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, and FATAL; in ascending order of priority. As we can see, log4j has corresponding printing methods for 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 method setLevel(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");
...

Go to page: 1  2  3  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Open Source Archives








JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Intel PDF: Virtualization Delivers Data Center Efficiency
Intel eBook: Managing the Evolving Data Center
Microsoft Article: BitLocker Brings Encryption to Windows Server 2008
Symantec eBook: The Guide to E-Mail Archiving and Management
Microsoft Article: RODCs Transform Branch Office Security
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
Avaya Article: Advancing the State of the Art in Customer Service
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Avaya Article: Avaya AE Services Provide Rapid Telephony Integration with Facebook
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Seminar: Efficiencies in Hardware/Software Virtualization
HP Webcast: Disaster Recovery Planning
Go Parallel Video: Performance and Threading Tools for Game Developers
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
IBM TCO eKIT: Your IT Budget is Under Attack, Get in Control
IBM Energy Efficiency eKIT: Learn How to Reduce Costs
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Microsoft Article: Silverlight Streaming--Free Video Hosting for All
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
HP Demo: StorageWorks EVA4400
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES