Logging with log4j: How and why you should use logging within your application.

Why should developers use logging?

Logging to those new in the development world is the process of putting output statements inside your code to facilitate debugging and analysis of performance or issues.  Development of an application is completed by going through a life-cycle that typically includes requirements, code production, testing, and deployment in some manor. Logging enables developers to easily debug their code while in the testing phase by readily seeing output of variables and trace statements placed in their code, also while in the deployment phase having logging set up can enable the developer to analyze where an error occurred if the application crashes or gets hung up.

Be warned though that logging can slow down an application if used excessively. Be sure to use as needed during development but in production only have logging enabled for critical sections of the code.

What is log4j?

Log4j is a popular logging package for the java language licensed under the Apache Software License. It enables a developer to easily add logging to their applications that is easily configurable on run-time to restrict which statements are to be logged, how they are formatted, and where they should be logged. For those who program in the C family of languages log4j has been ported to C, C++, C#, and other languages.

How do I use log4j?

To utilize log4j in your application you need to have the log4j jar file in the project library and have the main Logger class imported by the statement:

import org.apache.log4j.Logger

Once the Logger is imported you can instantiate it for a Class by using the getLogger method, I suggest creating a static logger property for your class you want to do logging in. The getLogger method takes a string parameter to define the logger instance it is common practice to use the Classes class as the value.

private static Logger log = Logger.getLogger( ClassName.class );

To log a statement you simply use the trace, debug, info, warn, error, and fatal methods. These will log the inputted string at the level that matches the method.

log.info( "my first log statement" );

At this point your logging statements are all set to go but you have not as yet defined where they should be outputted. For beginners it is best to use the BasicConfigurator to configure the Logger to ouput to the console. This is great for development purposes and as you get more advanced you can move on to Property and DOM Configurators that enable more advanced configurations. It is important to remember that the configuration only needs to be run once per application and should be done before any logging statements.

import org.apache.log4j.BasicConfigurator;


Comments & Questions

Add Your Comment