Browse DevX
Sign up for e-mail newsletters from DevX


Track Your Apps with the Open Source Logging Framework, Log4j : Page 3

As many developers can attest, logging is one of the most accessible ways to monitor the health and performance of your Java applications. Find out how Log4j, a logging framework from Apache, can handle both simple and advanced (multi-app, multi-machine) logging scenarios.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Only One Logger
As your program execution jumps from method to method within your code, it would be quite annoying to have to pass Logger references between methods. Fortunately, you don't have to. When you use the getLogger method with the same name, you are always returned a reference to the same Logger object. In the code below, both loggerA and loggerB point to the same Logger object in memory:

Logger loggerA = Logger.getLogger("com.someLogger"); Logger loggerB = Logger.getLogger("com.someLogger");

Appenders—Choosing What Log4j Writes To
In the SimpleLogger sample code, the first statement is:


This creates a basic Log4j setup that appends to the console. Dissecting one of our logs from the execution of SimpleLogger:

0 [main] WARN com.example.SimpleLogger - I am very thirsty

What information does the log statement above impart? First, that the number of milliseconds elapsed from the start of the program is zero (0); it then identifies the thread making the request (main), the level of the log statement (WARN), the name of the Logger making the request (com.example.SimpleLogger); and finally, the log statement itself (I am very thirsty). In a moment, you will see how you can customize the layout of what information is reported to you in your logs.

Log4j allows the programmer to have his logs written to a number of different types of output destinations. In Log4j terminology, the output destination is referred to as an Appender. Log4j has appenders for writing to the console, to files, NT Event Loggers, and much more.

You can associate multiple appenders to a single Logger. You associate an appender to a Logger simply by calling the addAppender method. I demonstrate this in the sample class, AppenderExample, some of which is grabbed below:

// create a console appender ConsoleAppender consoleAppender = new ConsoleAppender(myLayout); // create a file appender RollingFileAppender rollingFileAppender = null; try { rollingFileAppender = new RollingFileAppender(myLayout,"c:\\log4joutput.log",true); rollingFileAppender.setMaxFileSize("100KB"); } catch(Exception e) {} Logger myLogger = Logger.getLogger("com.example.AppenderExample"); // associate the appenders to the logger myLogger.addAppender(consoleAppender); myLogger.addAppender(rollingFileAppender);

In the code above, I associated a ConsoleAppender as well as a RollingFileAppender to the Logger object. The ConsoleAppender simply writes to the screen as my previous BasicConfigurator approach did. However, the RollingFileAppender is a bit more interesting. It allows me to write logs to a file (which I specified will be located at c:\log4joutput.log). I associated a Layout to each appender (which I will explain more about in the following section). Built into the RollingFileAppender is the ability to rollover files. Using the setMaxFileSize method, I state that once my log file reaches 100K, then older logs should automatically be moved to c:\log4joutput.log.1, c:\log4joutput.log.2, and so forth.

Adjusting Layout Using Patterns
The customizability of Log4j allows you to tailor the output of log statements to your liking. To customize the output format of your logs, you associate a layout to your appender (as I did in the AppenderExample sample class). Using an instance of org.apache.log4j.PatternLayout class, you can format your logging event as desired.

The PatternLayout object takes a conversion pattern string as an argument. It is this conversion pattern that will define the look of your log statements. These strings seem kind of perplexing (e.g., 4r [%t] %-5p %c %x - %m%n) The conversion pattern approach borrows from the C programming language, which uses a similar approach for its printf function.

The BasicConfigurator used in the SimpleLogger sample class uses a layout of: 4r [%t] %-5p %c %x - %m%n. As you saw from the sample output from that class, the default layout provides a good amount of information. However, we have a lot more information available to us (e.g., the time of the logging event and the line of the method in the code that wrote the log statement). You can learn more about how to tweak a conversion pattern string to your liking using the API for the PatternLayout class. I have provided a few demonstration formats in the sample class LayoutExample.

Configuring at Startup
As I stated earlier, one of the key capabilities of Log4j is being able to specify the configuration information at runtime. Previously, you set the level of logging using the setLevel method from the Logger instance.


This is not the usual way things are done in the real world. Rather, you would use the org.apache.log4j.PropertyConfigurator object as exemplified in PropertyConfiguratorExample.java to feed configuration information to your program at runtime. In the code, use the statement:


to grab the name of the Log4j properties file when our program is fired up. The contents of the sample properties configuration file named logging.properties (also downloadable in the project zip file) are shown below:

# Set the root logger level to DEBUG log4j.rootLogger=DEBUG, MyConsoleAppender # Set the logger level for com.example.PropertyConfigurator to error log4j.rootLogger=ERROR, MyConsoleAppender # create a ConsoleAppender log4j.appender.MyConsoleAppender=org.apache.log4j.ConsoleAppender # associate a pattern layout to the appender log4j.appender.MyConsoleAppender.layout=org.apache.log4j.PatternLayout log4j.appender.MyConsoleAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

Provide the name and location of the logging properties file as the program argument (e.g., c:\\logging.properties) to run the sample program.

Logging can have a material effect on the performance of your applications and should not be overlooked during your planning. See the sidebar "Performance Impact" to get some perspective on performance overhead with Log4j.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date