Documente Academic
Documente Profesional
Documente Cultură
Table of Contents
Point 9: Working with Log4j............................................................................................................1
Event Logging in Applications........................................................................................................2
Mechanism of Event Logging..................................................................................................2
Components of an Event Log.................................................................................................2
Logging Events with Log4j..............................................................................................................4
Packages in Log4j...................................................................................................................4
Overview of LogFactor5..........................................................................................................6
Components of Log4j.......................................................................................................................7
Logger Component.................................................................................................................7
Appender Component.............................................................................................................8
Layout Component..................................................................................................................9
Implementing Logging in Java Applications...............................................................................10
Configuring Log4j..................................................................................................................10
Using the BasicConfigurator Class.......................................................................................11
Implementing the RollingFileAppender and PatternLayout Classes.....................................12
Logging Messages to Windows Event Log...........................................................................15
Implementing a Customized Appender.................................................................................17
Related Topic..................................................................................................................................19
Event Category: Organizes events so that they can be filtered and viewed as needed. Event
categories are numbered starting from one and are placed in a separate message file or in
files that contain other messages.
Packages in Log4j
Log4j contains these nine packages that help in application logging:
org.apache.log4j Package: Logs specific operations. This is the main package of Log4j.
org.apache.log4j.config Package: Gets and sets the system properties.
org.apache.log4j.jdbc Package: Sends the log event details to a database.
org.apache.log4j.net Package: Logs remote applications.
org.apache.log4j.nt Package: Performs event logging in applications that run on the
Microsoft Windows NT platform.
org.apache.log4j.or Package: Delivers log messages based on the class that generates the
message.
org.apache.log4j.performance Package: Provides classes and interfaces to enhance the
performance of Log4j components.
org.apache.log4j.spi Package: Stores part of the System Programming Interface (SPI) that is
used to enhance the functions of Log4j.
org.apache.log4j.xml Package: Contains XMLbased components that are used to log data.
This package provides APIs, which enable configuration in the XML format.
The most important package of Log4j is org.apache.log4j. This package contains classes and
methods to perform specific logging functions. These classes are:
AppenderSkeleton Class: Supports filters and is the superclass for other appender classes.
It is an abstract class.
AsyncAppender Class: Retrieves events from the application and passes them to the
appender.
BasicConfigurator Class: Provides default configuration settings for log messages in the
absence of a configuration file.
ConsoleAppender Class: Appends the output of the log events to the standard output
stream, System.out.
Hierarchy Class: Maintains the logger hierarchy to retrieve loggers based on their names.
HTMLLayout Class: Generates output of log events in an HTML table format.
Layout Class: Creates a layout in the log format according to the end user requirement.
PatternLayout Class: Sends the outcome of the log event in the string format.
WriterAppender Class: Appends the log events using the source specified by the end user.
SimpleLayout Class: Specifies the log statement based on the priority level followed by the
log detail. The level and detail are separated by a hyphen.
FileAppender Class: Appends log messages to a file.
RollingFileAppender Class: Extends the FileAppender class and creates backup of log files
when the size of these files reaches a specified limit.
Reprinted for v697039, Verizon
Overview of LogFactor5
LogFactor5 is a Swingbased Graphical User Interface (GUI) written in Java and is as an additional
plugin utility for Log4j. When used in combination with debugging tools, such as Log4j, it provides
a powerful visual interface to organize log messages.
LogFactor5 supports various operating systems, such as Microsoft Windows 95, 98, NT, Linux, and
Sun Solaris. The advantages of LogFactor5 are:
Simplifies searching for messages
Displays log messages in a customized format
Reads a log file from a URL
Displays log messages of definite record size based on log configuration
Customizes the size and appearance of a log message
Supports all Log4j levels
Counts log messages dynamically
Components of Log4j
Log4j has three components: loggers, appenders, and layouts. These components are used to
generate different types of log messages according to the end user requirement.
Logger Component
The logger component describes a hierarchical structure for the log statements according to the end
user requirements. This component allows full control to enable or disable a log statement.
The logger component follows a specific naming convention. According to the hierarchical logger
naming rule:
"A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the
descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors
between itself and the descendant logger."
Every logging message has one of these priority levels associated with it:
DEBUG Priority: Performs debugging in the application. This type of a message is of the
lowest priority level.
INFO Priority: Provides information about the progress of the application.
WARN Priority: Issues warning statements when opening a file that should not be provided
access to.
ERROR Priority: Indicates the messages of the type ERROR.
FATAL Priority: Indicates the severity of an error in an application based on which the
application could fail. This type of message is of the highest priority level.
A logger name is followed by a dot and a sub class or method. When a logger is assigned a higher
level of priority, it is not possible to log messages with a lower priority level. Similarly, when a logger
is assigned with a lower level of priority, all other priorities at a level higher than the one assigned
can be used to log messages.
Table 291 shows how different types of loggers are assigned different levels:
Table 291: Logger Inheritance Level Case 1
Name of the Logger
Root
Scan
Scan.win
Scan.win.inst
In Table 291, the root logger is assigned a level Lroot and other loggers are not assigned any
levels. In such a situation, all loggers that follow the root logger inherit the root logger level.
Table 292 shows another situation in which different loggers are assigned different levels:
Reprinted for v697039, Verizon
In Table 292, the root logger, scan logger, and scan.win logger are assigned levels Lroot, Lscan,
and Lsw, respectively. The scan.win.inst logger is not assigned any level. As a result, the
scan.win.inst logger inherits a level, Lsw, from its parent scan.win level.
Table 293 describes a case in which all the levels are assigned and inherited by the loggers:
Table 293: Logger Inheritance Level Case 3
Name of the Logger
Root
Scan
scan.win
scan.win.inst
In Table 293, all the loggers are assigned a level. In this case, there is no need for inheritance
because all loggers inherit their own assigned levels.
Appender Component
The appender passes the output of a log to the required destination. It passes the log statements to
files, remotely located socket servers, and Windows NTbased event loggers.
The addAppender() method adds an appender to a logger. The default implementation for the
appender interface is provided in the abstract class AppenderSkeleton. This class provides
subclasses to support customized solutions depending on the requirement of the application. Some
of the important subclasses of the AppenderSkeleton class and the solutions provided by them are:
AsyncAppender Class: Allows logging events asynchronously. The class AsyncAppender
receives events and forwards them to multiple appenders. It is configured using the
DOMConfigurator class.
NTEventLogAppender Class: Allows logging events in the Windows NT Event Log. This
class is used exclusively for Windows systems.
NullAppender Class: Calls the format() method of the layout object when log messages are
not required to be written to a source.
SMTPAppender Class: Sends an email message to a specific ID or a group of IDs, in
response to an event, as specified while configuring Simple Mail Transfer Protocol(SMTP).
For example, the SMTPAppender class can send an email message to an administrator
when a specific event occurs.
SocketAppender Class: Logs events on a remote log server, usually a socketnode, which
reads LoggingEvent objects sent from a remote client using sockets. This process is known
Reprinted for v697039, Verizon
as remote logging.
FileAppender Class: Logs events to a log file. The log messages can be saved and used for
future reference.
ConsoleAppender Class: Appends log events to the standard output stream, System.out or
System.err, using the specified layout.
RollingFileAppender Class: Extends the FileAppender class and logs messages to a file. It
rolls back to the beginning of the file when the file reaches a certain size.
DailyRollingFileAppender Class: Extends the FileAppender class. This class logs the
messages to a log file on a periodical basis. The schedule is specified by the DatePattern
class, which should follow the pattern specified by the SimpleDateFormat class. The
schedule can be configured on an hourly, daily, weekly, monthly, minutely, or halfday basis.
Layout Component
The layout component customizes the output format in a predefined way. It helps to format a
logging request based on end user requirements. After the logging request is formatted, the
appender component sends the output to the destination.
The different types of layouts available in Log4j are:
DateLayout: Formats date related operations.
HTMLLayout: Displays events in an HTML table. This layout is useful in Webbased
applications because it helps monitor the log messages from a remote location.
PatternLayout: Formats the objects of the LoggingEvent class and displays them in the
string format. The string is formatted according to the conversion specification of the
PatternLayout class. Different format specifiers are available to format the string, such as
%5p [%t]: %m%n.
XMLLayout: Displays the messages in an XML format. The rules for this layout are specified
in document descriptor file log4j.dtd.
Configuring Log4j
Proper planning and designing is required for log messages. The number of log messages depends
upon the size and the complexity of an application. It is tedious to log messages when the number
of messages is high, because each application has to be modified and rebuilt before execution.
Log4j can be configured by using a configuration file. The configuration file is written in the XML or
Java properties format. Listing 291 details a sample configuration file for Log4j, which adheres to
the Java Properties file format:
Listing 291: Configuration File for Log4j in the Java Properties File Format
The log4j.rootConfigurator file declares as many appenders as required. In this example, three
appenders, A2, A3, and JDBC, are declared and are set to the priority DEBUG. The appenders are
initialized and the appender A2 is attached to the ConsoleAppender class and its layout is set to
PatternLayout. The appender A3 is attached to RollingFileAppender, which refers to a fixed file size.
On reaching the specified size, the contents of the file are deleted and logging is started from the
beginning of the file.
The configuration files can also be defined as XML files. The DOMConfigurator class is used for
XMLbased configuration. Listing 292 shows an XML file that configures Log4j:
Listing 292: XML Configuration File for Log4j
11
</appender>
<appender name="JDBC" class=" kar.log4j.examples.OurJDBCAppender">
<param name="url" value="jdbc:odbc:TestDSN" />
<param name="sqlPrefix" value="insert into LogTable(logmessage) values " />
<param name="username" value="nothing" />
<param name="passowrd" value="nothing" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%m"/>
</layout>
</appender>
<root>
<priority value ="DEBUG" class="org.apache.log4j.Priority "/>
<appenderref ref="A1" />
<appenderref ref="A2" />
<appenderref ref="A3" />
<appenderref ref="JDBC" />
</root>
</configuration>
To write log messages to the Windows NT Event Log, you can use the NTEventLogAppender class.
The JDBCAppender class and the variables are initialized with corresponding values and the
JDBCAppender class logs messages to the database.
The configuration files can be loaded into the program using the PropertyConfigurator class. The
static method configure is called by providing a string parameter to configure this class.
Listing 293 implements the code to create and implement the Calculate.java program:
Listing 293: The Calculate.java Program
import org.apache.log4j.*;
class BasicMath
{
Reprinted for v697039, Verizon
12
Figure 292 shows the output of the calculate program that displays the log messages:
13
3. Create an object of class Category using the getInstance() method in the name of the
respective class.
4. Use the PropertyConfigurator.configure() method to specify the configuration file that Log
APIs should follow.
5. Initialize the objects needed to implement database connections.
6. Create necessary string objects to store values from the database.
7. Create objects of the Connection, Statement, and ResultSet classes for database
connections.
package marketing;
import java.io.*;
import java.util.*;
import java.sql.*;
import org.apache.log4j.*;
public class ShowRecords
{
static Category cat = Category.getInstance(ShowRecords.class.getName());
public static void main(String s[])
{
PropertyConfigurator.configure(s[0]);
String id = new String();
String name=new String();
String add=new String();
String ph=new String();
String city=new String();
String state=new String();
String country=new String();
Connection con;
Statement smt;
ResultSet rs;
14
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:javadsn","","");
smt = con.createStatement();
String sql = "select * from emp";
rs = smt.executeQuery(sql);
while(rs.next())
{
name = rs.getString("name");
System.out.println("Name = "+name);
add = rs.getString("add");
System.out.println("Address = "+add);
ph = rs.getString("Ph");
System.out.println("Phone"+ph);
city = rs.getString("city");
System.out.println("City = "+city);
state = rs.getString("state");
System.out.println("State = "+state);
country = rs.getString("country");
System.out.println("Country = "+country);
}catch(Exception e)
{
cat.warn("Error In Application");
cat.debug((new java.util.Date()).toString() + e);
}
}
}
15
Listing 298 gives the code that accepts the user name and password and logs the user name in
an event log.
Listing 298: Implementing Logging in Windows NT
package samples.log4j;
import org.apache.log4j.*;
import org.apache.log4j.nt.*;
import java.io.*;
import java.util.*;
public class LoggingToNTEvent{
Reprinted for v697039, Verizon
16
In this program, the user name and password are accepted and the information is appended to the
system date. The final message is logged to the Windows NT Event Log.
Figure 294 depicts the message stored in the Windows NT Event Log:
17
18
}catch(Exception e){
System.out.println(e);
}
}
public boolean requiresLayout(){
return true;
}
}
log4j.rootCategory=DEBUG, JDBC
log4j.appender.JDBC=kar.log4j.examples.OurJDBCAppender
log4j.appender.JDBC.layout=org.apache.log4j.PatternLayout
log4j.appender.JDBC.layout.ConversionPattern=%m
log4j.appender.JDBC.url=jdbc:odbc:TestDSN
log4j.appender.JDBC.sqlPrefix=insert into LogTable(LogMessage) values
log4j.appender.JDBC.username=nothing
log4j.appender.JDBC.password=nothing
Figure 295 shows the log messages stored in a Microsoft Access database by the Customized
JDBC Appender:
Related Topic
For related information on this topic, you can refer to the Creating Custom Layout Managers
ReferencePoint.