Você está na página 1de 21

All rights reserved.

Reproduction and/or distribution in whole or in


part in electronic, paper or other forms without written permission
is prohibited.

Java ReferencePoint Suite


SkillSoft Corporation. (c) 2002. Copying Prohibited.

Reprinted for Balaji Nallathambi, Verizon


Balaji@verizon.com
Reprinted with permission as a subscription benefit of Books24x7,
http://www.books24x7.com/

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

Point 9: Working with Log4j


K. Parthasarthy
Logging helps debug errors in applications. A log file records the events and errors generated by
specific lines of code and allows you to pinpoint errors in applications.
The Apache Software Foundation developed Log4j to enable logging in applications. Log4j
separates the application source code and log statements, helps store these statements in a
separate file, and provides the logging statements at application runtime. This tool enables logging
without modifying the application code. Log4j also helps run the application faster and more
efficiently than other logging processes.
This ReferencePoint explains how to enable event logging in applications using Log4j. It also details
the advantages and components of Log4j, discusses the packages used in Log4j, and provides an
overview of LogFactor5.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Event Logging in Applications


After implementing the logging process in an application, it is not necessary to debug each line of
the application separately. The statements generated during logging can be used to prepare a
detailed error report, which can be used to solve application errors. You need not perform
debugging operations at the client side. The system administrators or the service engineers at the
client side can rectify the errors in the application based on the log report generated by the logging
process.

Mechanism of Event Logging


The event log is the main storage location for all log events generated by applications or the
operating system. When an operating system or an application reports an event, the event log
records it along with other necessary information, such as date, time, and log messages, and stores
it in a log file. Figure 291 illustrates the mechanism of event logging:

Figure 291: Mechanism of Event Logging

Components of an Event Log


An event log consists of several components, such as Log files, event sources, event messages,
event identifiers, and event categories, which perform different logging activities in an application.
The components of an event log are:
Log File: Stores the events generated by the applications and servers. The log files available
in an event log are application log file, security log file, and system log file. The application
log file logs information related to the application, the security log file stores information
about files that have been accessed and modified, and the system log file logs audit events.
Event Source: Specifies the name of the application that logs the event.
Event Message: Stores the detailed description of the log events. The information stored in
the event message file is languagedependent.
Event Identifier: Detects a specific type of event. The event identifier describes its own
numbered events and the description strings to which it is charted.
Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

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.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Logging Events with Log4j


Log4j reduces the effort in writing log statements while developing an application. Whenever Log4j
encounters an error, it records the error in a log file and generates the file identification number and
an error code. The errors generated by the application at runtime can be located easily and
debugged without modifying the application program.
The log statements can be customized and sent to different data sources, such as files and
databases. The output can also be enabled or disabled so that selective log statements can be
viewed.
This concept of logging at runtime reduces the workload of the application and increases its
efficiency. Log4j also increases the flexibility of an application to access a log file at runtime. It does
not produce any unexpected exceptions, which prevents the breakdown of the application. If the
logging activities cannot be performed, Log4j shows an error message, which signifies that the
action cannot be performed.
Some of the other advantages of Log4j are:
Performs threading and is thread safe
Handles Java exceptions
Configures logging during the application runtime
Sends output to a file, remote server, or through email
Customizes the format of output using a layout class
Follows the logger hierarchy
Reduces operational cost

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.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

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

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

PropertyConfigurator Class: Retrieves configuration information from external files.


Category Class: Provides information about the categories in a hierarchy of messages.
Priority Class: Describes priorities, such as FATAL, ERROR, WARN, INFO, and DEBUG,
which are accepted by the system.

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

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

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

Level Assigned to the Logger


Lroot
Nil
Nil
Nil

Level Inherited by the Logger


Lroot
Lroot
Lroot
Lroot

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

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

Table 292: Logger Inheritance Level Case 2


Name of the Logger
Root
Scan
scan.win
scan.win.inst

Level Assigned to the Logger


Lroot
Lscan
Lsw
Nil

Level Inherited by the Logger


Lroot
Lscan
Lsw
Lsw

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

Level Assigned to the Logger


Lroot
Lscan
Lsw
Lswi

Level Inherited by the Logger


Lroot
Lscan
Lsw
Lswi

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

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

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.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Implementing Logging in Java Applications


Log4j has minimal effect on the performance of an application during logging. Its packages are
simple to understand and easy to implement. As a result, it is easy to maintain the application
because the configuration details, such as logging resource and logging format, are provided in the
configuration file.

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

log4j.rootCategory=DEBUG, A1, A3, JDBC, A2


log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
#log4j.appender.A2=org.apache.log4j.nt.NTEventLogAppender
#log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A3=org.apache.log4j.RollingFileAppender
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.File=example.log
log4j.appender.A3.MaxFileSize=200KB
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

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

<?xml version="1.0" encoding="UTF8" ?>


<configuration configDebug="true">
<appender name="A1" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
</layout>
</appender>
<appender name="A2" class="org.apache.log4j.nt.NTEventLogAppender
">
<layout class="org.apache.log4j.PatternLayout">
</layout>
</appender>
<appender name="A3" class="org.apache.log4j.RollingFileAppender
">
<param name="File" value="example.log" />
<param name="MaxFileSize" value="200KB" />
<layout class="org.apache.log4j.PatternLayout">
</layout>
Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

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.

Using the BasicConfigurator Class


This section explains a program that performs a simple calculation of dividing a number by another
by using the BasicConfigurator class. If an exception arises, a log message is displayed in the
console.
Creating and Implementing the BasicConfigurator Class
To create and implement the BasicConfigurator class that implements the program, first import the
required packages and create the classes and methods needed to perform the logging activities.
The steps to implement the program are:
1. Create a class BasicMath in which the logging activities are performed.
2. Create an object of the Category class by using the getInstance() method.
3. Create a method divide(), which accepts two parameters of the type int.
4. Perform the division and display the result in the console.
5. Use the BasicConfigurator.configure() method to implement the default Log4j configuration.
6. Raise log messages based on the category of error, such as info and fatal.

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

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

12

static Category cat = Category.getInstance(BasicMath.class.getName());


public void divide(int a, int b)
{
BasicConfigurator.configure();
cat.info("Entering application.");
try
{
System.out.println("Answer ="+a/b);
cat.info("Processing Done.");
}catch(Exception e)
{
cat.fatal("Application crashed due to invalid parameters");
}
}
}

Invoking the Logging Methods


To invoke logging methods, you can create a class Calculate, which invokes the methods from the
BasicMath class by creating an object of the BasicMath class. Listing 294 details the code for the
class Calculate containing method main():
Listing 294: Implementing Logging within the main() Method
public class Calculate
{
public static void main(String[] args)
{
BasicMath obj = new BasicMath();
obj.divide(10,20);
obj.divide(10,0);
}
}

Figure 292 shows the output of the calculate program that displays the log messages:

Figure 292: Output of the Calculate Program

Implementing the RollingFileAppender and PatternLayout Classes


This section discusses the implementation of the RollingFileAppender and PatternLayout classes
using an example program. In the program, records from a table, emp, are retrieved and displayed.
Initializing Objects for Database Connectivity
The ShowRecords.java program explains how to create classes and objects to implement database
connectivity. To create the ShowRecords.java program:
1. Import the necessary packages to implement Log4j.
2. Create a class ShowRecords containing the method main().
Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

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.

Listing 295 details the code of the ShowRecords.java program:


Listing 295: The ShowRecords.java Program

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;

Displaying Records and Logging Messages


After initializing objects for database connectivity, the database connection is established and
records are retrieved from the database. To establish database connectivity, retrieve records and
log messages:
1. Initialize the driver to connect to the database.
2. Initialize the connection object using the DriverManager.getConnection() method.
3. Assign the SQL statement to the String sql.
4. Execute the SQL statement.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

14

5. Assign the values to the appropriate variables.


6. Print the values to the console.
7. Log messages based on their type, such as warning and debug.

Listing 296 details the code for database connectivity:


Listing 296: Establishing Database Connection

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);
}
}
}

Configuring the Log4j Properties


To run the ShowRecords.java program, modify the configuration file. This file contains the details of
the source where messages are logged and the layout of the messages. To modify the
configuration file:
1. Set the category types and the priority.
2. Assign the appenders to the appender keys.
3. Assign the Layout type.
4. If the appender type is RollingFileAppender, assign the file name to log messages.
5. If the appender type is RollingFileAppender, assign the MaxFileSize value according to the
Key.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

15

Listing 297 details the configuration details of Log4j:


Listing 297: Configuration Details of Log4j
log4j.rootCategory=DEBUG ,AP
log4j.appender.AP=org.apache.log4j.RollingFileAppender
log4j.appender.AP.layout=org.apache.log4j.PatternLayout
log4j.appender.AP.File=example.log
log4j.appender.AP.MaxFileSize=200KB

Figure 293 shows the contents of the log file, example.log:

Figure 293: Sample Log File

Logging Messages to Windows Event Log


In Windows NT, log messages are classified into different categories. To log information in a
Windows log file, Log4j provides a Dynamic Linked Library (DLL) file that has to be placed in the
WinNT/System32 folder in Windows NT. This program accepts the user name and password and
logs the values to Windows NT Event logger with date and time.
Creating Classes and Implementing Logging
In this section, a program accepts the user name and password from the end user and logs the
name of the user and time of login to an event log. To implement the program:
1. Import the necessary packages for logging.
2. Create a class LoggingToNtEvent and define a method main().
3. Create an object of the Category class using the Category.getInstance() method. The object
should have the same name as the LoggingToNTEvent class.
4. Accept the user name and password from the end user and log the information to the source
specified by the Appender.

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

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

16

static Category cat = Category.getInstance(LoggingToNTEvent.class.getName());


public static void main(String args[]){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)
System.out.println("Specify Login Name\n");
String login = br.readLine();
System.out.println("Specify Password\n");
String password = br.readLine();
PropertyConfigurator.configure(args[0]);
cat.info("Entering application.");
cat.info(login + "logged in @ "+ (new Date()).toString());
}catch(Exception e){
cat.warn("Error Occurred "+e);
}
}
}

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:

Figure 294: Storing a Message in Event Log


The conf.properties Configuration File
In the conf.properties configuration file, the appender is assigned to
org.apache.log4j.nt.NTEventLogAppender. As a result, the messages are logged to WindowsNT
Event Log. The configuration file is shown here:
log4j.rootCategory=DEBUG ,A1,
log4j.appender.A1=org.apache.log4j.nt.NTEventLogAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

17

Implementing a Customized Appender


You can create a customized appender to log specific messages for your applications. This section
creates a customized JDBC appender, which can be used to log messages to a database. When
you create a customized appender, you also need to modify the configuration file, steps for which
are listed in this section.
Creating Customized JDBC Appender
The customized JDBC appender, OurJDBCAppender, is created in the kar.log4j.examples package
and it extends the AppenderSkeleton class. Listing 299 shows the code for the customized
appender:
Listing 299: The OurJDBCAppender Program
package kar.log4j.examples;
import java.sql.*;
import org.apache.log4j.*;
import org.apache.log4j.spi.*;
public class OurJDBCAppender extends AppenderSkeleton{
String url;
String sqlPrefix;
String username;
String password;
String message;
String sql;
Connection con;
Statement stmt;
public OurJDBCAppender(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}catch(Exception e){
System.out.println(e);
}
}
public void setUrl(String s){
url = s;
}
public void setSqlPrefix(String s){
sqlPrefix = s;
}
public void setUsername(String s){
if(s.equals("nothing")){
username = "";
}else{
username=s;
}
}
public void setPassword(String s){
if(s.equals("nothing")){
password = "";
}else{
password=s;
}
}
public void append(LoggingEvent le){
message = layout.format(le);
sql = sqlPrefix + "('"+message+"')";
System.out.println("From Appender : "+sql);
//do JDBC Operations
try{
con = DriverManager.getConnection(url,username,password);
stmt = con.createStatement();
stmt.executeUpdate(sql);
}catch(Exception e){
System.out.println(e);
}
}
public void close(){
try{
con.commit();
Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

18

}catch(Exception e){
System.out.println(e);
}
}
public boolean requiresLayout(){
return true;
}
}

How the JDBC Appender Works


The customized appender logs the messages into a database table by using the JDBC API. It is
mandatory to override the append(), close(), and requiresLayout() methods of the
AppenderSkeleton class because these methods implement the functionality of the application. The
remaining methods are used to initialize the declared fields, which are obtained from the
configuration file. This file can be in the Java Properties file or XML format.
The append() method takes an object of the LoggingEvent class as a parameter. This parameter
encapsulates the Category object, a fullqualified name of the Category class, a message, and the
priority. The AppenderSkeleton class encapsulates the layout of the logging messages.
To perform logging activities, invoke the format() method and pass the LoggingEvent object to it.
The layout class formats the message according to a specific format and returns a string. The
configuration file contains the SQL statement to log messages. The appender retrieves the SQL
statement from the configuration file and logs messages in to the database.
Listing 2910 details the configuration file for customized the appender:
Listing 2910: The Configuration File for the Customized Appender

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:

Figure 295: Log Messages in Tabular Format

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Related Topic
For related information on this topic, you can refer to the Creating Custom Layout Managers
ReferencePoint.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Você também pode gostar