working with log4j

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 [email protected] Reprinted with permission as a subscription benefit of Books24x7, http://www.books24x7.com/

Upload: debojyotis

Post on 26-Sep-2015

17 views

Category:

Documents


0 download

DESCRIPTION

log4j

TRANSCRIPT

  • All rights reserved. Reproduction and/or distribution in whole or inpart in electronic, paper or other forms without written permission

    is prohibited.

    Java ReferencePoint SuiteSkillSoft Corporation. (c) 2002. Copying Prohibited.

    Reprinted for Balaji Nallathambi, [email protected] 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

    i

  • Point 9: Working with Log4jK. ParthasarthyLogging helps debug errors in applications. A log file records the events and errors generated byspecific lines of code and allows you to pinpoint errors in applications.

    The Apache Software Foundation developed Log4j to enable logging in applications. Log4jseparates the application source code and log statements, helps store these statements in aseparate file, and provides the logging statements at application runtime. This tool enables loggingwithout modifying the application code. Log4j also helps run the application faster and moreefficiently than other logging processes.

    This ReferencePoint explains how to enable event logging in applications using Log4j. It also detailsthe advantages and components of Log4j, discusses the packages used in Log4j, and provides anoverview of LogFactor5.

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • Event Logging in ApplicationsAfter implementing the logging process in an application, it is not necessary to debug each line ofthe application separately. The statements generated during logging can be used to prepare adetailed error report, which can be used to solve application errors. You need not performdebugging operations at the client side. The system administrators or the service engineers at theclient side can rectify the errors in the application based on the log report generated by the loggingprocess.

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

    Figure 291: Mechanism of Event LoggingComponents of an Event LogAn 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 availablein an event log are application log file, security log file, and system log file. The applicationlog file logs information related to the application, the security log file stores informationabout 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 inthe event message file is languagedependent.

    Event Identifier: Detects a specific type of event. The event identifier describes its ownnumbered events and the description strings to which it is charted.

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • Event Category: Organizes events so that they can be filtered and viewed as needed. Eventcategories are numbered starting from one and are placed in a separate message file or infiles that contain other messages.

    Java ReferencePoint Suite 3

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • Logging Events with Log4jLog4j reduces the effort in writing log statements while developing an application. Whenever Log4jencounters an error, it records the error in a log file and generates the file identification number andan error code. The errors generated by the application at runtime can be located easily anddebugged without modifying the application program.

    The log statements can be customized and sent to different data sources, such as files anddatabases. The output can also be enabled or disabled so that selective log statements can beviewed.

    This concept of logging at runtime reduces the workload of the application and increases itsefficiency. Log4j also increases the flexibility of an application to access a log file at runtime. It doesnot produce any unexpected exceptions, which prevents the breakdown of the application. If thelogging activities cannot be performed, Log4j shows an error message, which signifies that theaction 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 Log4jLog4j 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 theMicrosoft Windows NT platform.

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • org.apache.log4j.or Package: Delivers log messages based on the class that generates themessage.

    org.apache.log4j.performance Package: Provides classes and interfaces to enhance theperformance of Log4j components.

    org.apache.log4j.spi Package: Stores part of the System Programming Interface (SPI) that isused 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 andmethods 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 theappender.

    BasicConfigurator Class: Provides default configuration settings for log messages in theabsence of a configuration file.

    ConsoleAppender Class: Appends the output of the log events to the standard outputstream, 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 thelog 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 fileswhen the size of these files reaches a specified limit.

    Java ReferencePoint Suite 5

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 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 LogFactor5LogFactor5 is a Swingbased Graphical User Interface (GUI) written in Java and is as an additionalplugin utility for Log4j. When used in combination with debugging tools, such as Log4j, it providesa powerful visual interface to organize log messages.

    LogFactor5 supports various operating systems, such as Microsoft Windows 95, 98, NT, Linux, andSun 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

    Java ReferencePoint Suite 6

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • Components of Log4jLog4j has three components: loggers, appenders, and layouts. These components are used togenerate different types of log messages according to the end user requirement.

    Logger ComponentThe logger component describes a hierarchical structure for the log statements according to the enduser 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 loggernaming rule:

    "A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of thedescendant logger name. A logger is said to be a parent of a child logger if there are no ancestorsbetween 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 thelowest 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 providedaccess to.

    ERROR Priority: Indicates the messages of the type ERROR.

    FATAL Priority: Indicates the severity of an error in an application based on which theapplication 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 higherlevel of priority, it is not possible to log messages with a lower priority level. Similarly, when a loggeris assigned with a lower level of priority, all other priorities at a level higher than the one assignedcan 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 Level Assigned to the Logger Level Inherited by the LoggerRoot Lroot LrootScan Nil LrootScan.win Nil LrootScan.win.inst Nil Lroot

    In Table 291, the root logger is assigned a level Lroot and other loggers are not assigned anylevels. 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

  • Table 292: Logger Inheritance Level Case 2

    Name of the Logger Level Assigned to the Logger Level Inherited by the LoggerRoot Lroot LrootScan Lscan Lscanscan.win Lsw Lswscan.win.inst Nil 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, thescan.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 Level Assigned to the Logger Level Inherited by the LoggerRoot Lroot LrootScan Lscan Lscanscan.win Lsw Lswscan.win.inst Lswi Lswi

    In Table 293, all the loggers are assigned a level. In this case, there is no need for inheritancebecause all loggers inherit their own assigned levels.

    Appender ComponentThe appender passes the output of a log to the required destination. It passes the log statements tofiles, remotely located socket servers, and Windows NTbased event loggers.

    The addAppender() method adds an appender to a logger. The default implementation for theappender interface is provided in the abstract class AppenderSkeleton. This class providessubclasses to support customized solutions depending on the requirement of the application. Someof the important subclasses of the AppenderSkeleton class and the solutions provided by them are:

    AsyncAppender Class: Allows logging events asynchronously. The class AsyncAppenderreceives events and forwards them to multiple appenders. It is configured using theDOMConfigurator class.

    NTEventLogAppender Class: Allows logging events in the Windows NT Event Log. Thisclass is used exclusively for Windows systems.

    NullAppender Class: Calls the format() method of the layout object when log messages arenot required to be written to a source.

    SMTPAppender Class: Sends an email message to a specific ID or a group of IDs, inresponse to an event, as specified while configuring Simple Mail Transfer Protocol(SMTP).For example, the SMTPAppender class can send an email message to an administratorwhen a specific event occurs.

    SocketAppender Class: Logs events on a remote log server, usually a socketnode, whichreads LoggingEvent objects sent from a remote client using sockets. This process is known

    Java ReferencePoint Suite 8

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • as remote logging.

    FileAppender Class: Logs events to a log file. The log messages can be saved and used forfuture reference.

    ConsoleAppender Class: Appends log events to the standard output stream, System.out orSystem.err, using the specified layout.

    RollingFileAppender Class: Extends the FileAppender class and logs messages to a file. Itrolls back to the beginning of the file when the file reaches a certain size.

    DailyRollingFileAppender Class: Extends the FileAppender class. This class logs themessages to a log file on a periodical basis. The schedule is specified by the DatePatternclass, which should follow the pattern specified by the SimpleDateFormat class. Theschedule can be configured on an hourly, daily, weekly, monthly, minutely, or halfday basis.

    Layout ComponentThe layout component customizes the output format in a predefined way. It helps to format alogging request based on end user requirements. After the logging request is formatted, theappender 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 Webbasedapplications because it helps monitor the log messages from a remote location.

    PatternLayout: Formats the objects of the LoggingEvent class and displays them in thestring format. The string is formatted according to the conversion specification of thePatternLayout 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 specifiedin document descriptor file log4j.dtd.

    Java ReferencePoint Suite 9

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • Implementing Logging in Java ApplicationsLog4j has minimal effect on the performance of an application during logging. Its packages aresimple to understand and easy to implement. As a result, it is easy to maintain the applicationbecause the configuration details, such as logging resource and logging format, are provided in theconfiguration file.

    Configuring Log4jProper planning and designing is required for log messages. The number of log messages dependsupon the size and the complexity of an application. It is tedious to log messages when the numberof 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 orJava properties format. Listing 291 details a sample configuration file for Log4j, which adheres tothe Java Properties file format:Listing 291: Configuration File for Log4j in the Java Properties File Format

    log4j.rootCategory=DEBUG, A1, A3, JDBC, A2log4j.appender.A1=org.apache.log4j.ConsoleAppenderlog4j.appender.A1.layout=org.apache.log4j.PatternLayout#log4j.appender.A2=org.apache.log4j.nt.NTEventLogAppender#log4j.appender.A2.layout=org.apache.log4j.PatternLayoutlog4j.appender.A3=org.apache.log4j.RollingFileAppenderlog4j.appender.A3.layout=org.apache.log4j.PatternLayoutlog4j.appender.A3.File=example.loglog4j.appender.A3.MaxFileSize=200KBlog4j.appender.JDBC=kar.log4j.examples.OurJDBCAppenderlog4j.appender.JDBC.layout=org.apache.log4j.PatternLayoutlog4j.appender.JDBC.layout.ConversionPattern=%mlog4j.appender.JDBC.url=jdbc:odbc:TestDSNlog4j.appender.JDBC.sqlPrefix=insert into LogTable(LogMessage) valueslog4j.appender.JDBC.username=nothinglog4j.appender.JDBC.password=nothing

    The log4j.rootConfigurator file declares as many appenders as required. In this example, threeappenders, A2, A3, and JDBC, are declared and are set to the priority DEBUG. The appenders areinitialized and the appender A2 is attached to the ConsoleAppender class and its layout is set toPatternLayout. 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 thebeginning of the file.

    The configuration files can also be defined as XML files. The DOMConfigurator class is used forXMLbased configuration. Listing 292 shows an XML file that configures Log4j:Listing 292: XML Configuration File for Log4j

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 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 theJDBCAppender class logs messages to the database.

    The configuration files can be loaded into the program using the PropertyConfigurator class. Thestatic method configure is called by providing a string parameter to configure this class.

    Using the BasicConfigurator ClassThis section explains a program that performs a simple calculation of dividing a number by anotherby using the BasicConfigurator class. If an exception arises, a log message is displayed in theconsole.

    Creating and Implementing the BasicConfigurator Class

    To create and implement the BasicConfigurator class that implements the program, first import therequired packages and create the classes and methods needed to perform the logging activities.The steps to implement the program are:

    Create a class BasicMath in which the logging activities are performed.1.

    Create an object of the Category class by using the getInstance() method.2.

    Create a method divide(), which accepts two parameters of the type int.3.

    Perform the division and display the result in the console.4.

    Use the BasicConfigurator.configure() method to implement the default Log4j configuration.5.

    Raise log messages based on the category of error, such as info and fatal.6.

    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{

    Java ReferencePoint Suite 11

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 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 theBasicMath class by creating an object of the BasicMath class. Listing 294 details the code for theclass Calculate containing method main():Listing 294: Implementing Logging within the main() Methodpublic 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 ProgramImplementing the RollingFileAppender and PatternLayout ClassesThis section discusses the implementation of the RollingFileAppender and PatternLayout classesusing an example program. In the program, records from a table, emp, are retrieved and displayed.

    Initializing Objects for Database ConnectivityThe ShowRecords.java program explains how to create classes and objects to implement databaseconnectivity. To create the ShowRecords.java program:

    Import the necessary packages to implement Log4j.1.

    Create a class ShowRecords containing the method main().2.

    Java ReferencePoint Suite 12

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • Create an object of class Category using the getInstance() method in the name of therespective class.

    3.

    Use the PropertyConfigurator.configure() method to specify the configuration file that LogAPIs should follow.

    4.

    Initialize the objects needed to implement database connections.5.

    Create necessary string objects to store values from the database.6.

    Create objects of the Connection, Statement, and ResultSet classes for databaseconnections.

    7.

    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 andrecords are retrieved from the database. To establish database connectivity, retrieve records andlog messages:

    Initialize the driver to connect to the database.1.

    Initialize the connection object using the DriverManager.getConnection() method.2.

    Assign the SQL statement to the String sql.3.

    Execute the SQL statement.4.

    Java ReferencePoint Suite 13

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • Assign the values to the appropriate variables.5.

    Print the values to the console.6.

    Log messages based on their type, such as warning and debug.7.

    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 PropertiesTo run the ShowRecords.java program, modify the configuration file. This file contains the details ofthe source where messages are logged and the layout of the messages. To modify theconfiguration file:

    Set the category types and the priority.1.

    Assign the appenders to the appender keys.2.

    Assign the Layout type.3.

    If the appender type is RollingFileAppender, assign the file name to log messages.4.

    If the appender type is RollingFileAppender, assign the MaxFileSize value according to theKey.

    5.

    Java ReferencePoint Suite 14

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • Listing 297 details the configuration details of Log4j:Listing 297: Configuration Details of Log4jlog4j.rootCategory=DEBUG ,APlog4j.appender.AP=org.apache.log4j.RollingFileAppenderlog4j.appender.AP.layout=org.apache.log4j.PatternLayoutlog4j.appender.AP.File=example.loglog4j.appender.AP.MaxFileSize=200KB

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

    Figure 293: Sample Log FileLogging Messages to Windows Event LogIn Windows NT, log messages are classified into different categories. To log information in aWindows log file, Log4j provides a Dynamic Linked Library (DLL) file that has to be placed in theWinNT/System32 folder in Windows NT. This program accepts the user name and password andlogs 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 thename of the user and time of login to an event log. To implement the program:

    Import the necessary packages for logging.1.

    Create a class LoggingToNtEvent and define a method main().2.

    Create an object of the Category class using the Category.getInstance() method. The objectshould have the same name as the LoggingToNTEvent class.

    3.

    Accept the user name and password from the end user and log the information to the sourcespecified by the Appender.

    4.

    Listing 298 gives the code that accepts the user name and password and logs the user name inan 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{

    Java ReferencePoint Suite 15

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 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 thesystem 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 LogThe conf.properties Configuration File

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

    Java ReferencePoint Suite 16

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • Implementing a Customized AppenderYou can create a customized appender to log specific messages for your applications. This sectioncreates a customized JDBC appender, which can be used to log messages to a database. Whenyou create a customized appender, you also need to modify the configuration file, steps for whichare listed in this section.

    Creating Customized JDBC Appender

    The customized JDBC appender, OurJDBCAppender, is created in the kar.log4j.examples packageand it extends the AppenderSkeleton class. Listing 299 shows the code for the customizedappender:

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

    Java ReferencePoint Suite 17

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • }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 ismandatory to override the append(), close(), and requiresLayout() methods of theAppenderSkeleton class because these methods implement the functionality of the application. Theremaining methods are used to initialize the declared fields, which are obtained from theconfiguration 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 parameterencapsulates the Category object, a fullqualified name of the Category class, a message, and thepriority. 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. Theconfiguration file contains the SQL statement to log messages. The appender retrieves the SQLstatement 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, JDBClog4j.appender.JDBC=kar.log4j.examples.OurJDBCAppenderlog4j.appender.JDBC.layout=org.apache.log4j.PatternLayoutlog4j.appender.JDBC.layout.ConversionPattern=%mlog4j.appender.JDBC.url=jdbc:odbc:TestDSNlog4j.appender.JDBC.sqlPrefix=insert into LogTable(LogMessage) valueslog4j.appender.JDBC.username=nothinglog4j.appender.JDBC.password=nothing

    Figure 295 shows the log messages stored in a Microsoft Access database by the CustomizedJDBC Appender:

    Figure 295: Log Messages in Tabular Format

    Java ReferencePoint Suite 18

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • Related TopicFor related information on this topic, you can refer to the Creating Custom Layout ManagersReferencePoint.

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

    Table of Contents Point 9: Working with Log4j Event Logging in Applications Mechanism of Event Logging Components of an Event Log

    Logging Events with Log4j Packages in Log4j Overview of LogFactor5

    Components of Log4j Logger Component Appender Component Layout Component

    Implementing Logging in Java Applications Configuring Log4j Using the BasicConfigurator Class Implementing the RollingFileAppender and PatternLayout Classes Logging Messages to Windows Event Log Implementing a Customized Appender

    Related Topic