Streamline Common Base Event logging Before you startconfiguration errors, performance degradation,...

23
© Copyright IBM Corporation 2006 Trademarks Streamline Common Base Event logging Page 1 of 23 Streamline Common Base Event logging Reduce complexity and instrumentation code size Paul Slauenwhite January 03, 2006 Common Base Event logging provides problem-determination data rich in activity and control- flow information that the Log and Trace Analyzer uses to accelerate problem determination and increase system serviceability and quality. This tutorial shows how to streamline Common Base Event logging instrumentation in the Java™ programming language to reduce complexity and instrumentation code size. You'll learn techniques and best practices that reduce maintenance requirements and let you increase customized, vendor-specific content. Before you start About this tutorial The Log and Trace Analyzer (LTA) in the IBM Autonomic Computing Toolkit monitors, correlates, analyzes, diagnoses, and resolves run-time problems in complex heterogeneous systems. The LTA collects and consolidates practical problem-determination data in the Common Base Event format from disparate systems into a single management tool. You can then use the LTA for viewing, navigating, sorting, filtering, searching, correlating, and analyzing. My previous tutorial, "Common Base Event Logging" (see Resources), showed how to configure Common Base Event logging in the Java language. This gives you a rich source of activity and control-flow information to accelerate problem determination and increase system serviceability and quality. The LTA can then use logged Common Base Events to detect and resolve configuration errors, performance degradation, exception states, resource starvation, security failures, communication delays, deadlocking, and other problems. However, a common criticism of Common Base Event logging is that it is too heavyweight for simple message logging, causing increased complexity, instrumentation code size, and maintenance. This tutorial shows how to streamline Common Base Event logging to mitigate these issues. The tutorial: • Reviews the concept of problem determination and the Common Base Event model. The review details the benefits of and concerns with logging events and problems in the Common Base Event format.

Transcript of Streamline Common Base Event logging Before you startconfiguration errors, performance degradation,...

Page 1: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

© Copyright IBM Corporation 2006 TrademarksStreamline Common Base Event logging Page 1 of 23

Streamline Common Base Event loggingReduce complexity and instrumentation code size

Paul Slauenwhite January 03, 2006

Common Base Event logging provides problem-determination data rich in activity and control-flow information that the Log and Trace Analyzer uses to accelerate problem determination andincrease system serviceability and quality. This tutorial shows how to streamline Common BaseEvent logging instrumentation in the Java™ programming language to reduce complexity andinstrumentation code size. You'll learn techniques and best practices that reduce maintenancerequirements and let you increase customized, vendor-specific content.

Before you startAbout this tutorialThe Log and Trace Analyzer (LTA) in the IBM Autonomic Computing Toolkit monitors, correlates,analyzes, diagnoses, and resolves run-time problems in complex heterogeneous systems. TheLTA collects and consolidates practical problem-determination data in the Common Base Eventformat from disparate systems into a single management tool. You can then use the LTA forviewing, navigating, sorting, filtering, searching, correlating, and analyzing.

My previous tutorial, "Common Base Event Logging" (see Resources), showed how to configureCommon Base Event logging in the Java language. This gives you a rich source of activity andcontrol-flow information to accelerate problem determination and increase system serviceabilityand quality. The LTA can then use logged Common Base Events to detect and resolveconfiguration errors, performance degradation, exception states, resource starvation, securityfailures, communication delays, deadlocking, and other problems. However, a common criticismof Common Base Event logging is that it is too heavyweight for simple message logging, causingincreased complexity, instrumentation code size, and maintenance. This tutorial shows how tostreamline Common Base Event logging to mitigate these issues.

The tutorial:

• Reviews the concept of problem determination and the Common Base Event model. Thereview details the benefits of and concerns with logging events and problems in the CommonBase Event format.

Page 2: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

developerWorks® ibm.com/developerWorks/

Streamline Common Base Event logging Page 2 of 23

• Teaches best practices that let you streamline Common Base Event logging instrumentationin the Java programming language to reduce complexity and instrumentation code size.

• Shows how to leverage the Common Base Event factory to create a customized XMLconfiguration template for populating Common Base Events with static system-specificcontent.

• Shows how to extend the Common Base Event factory to create a customized Event FactoryHome for retrieving the same static system-specific content set as part of the Java Loggingconfiguration (for example, java.util.Properties configuration file) and retrieved from JavaLogging's Log Manager.

• Shows how to create a customized Content Handler for populating Common Base Eventswith dynamically resolved run-time content.

• Shows how to merge the Event Factory Home and Content Handler for streamlined CommonBase Event logging based on the system's logging configuration file and run time to decreasemaintenance and increase customized, vendor-specific content.

Developers can use the best practices and techniques in this tutorial when instrumenting theircode for Common Base Event logging, but they are intended primarily for system serviceabilityarchitects. Serviceability architects provide a logging strategy for the complete system thatindividual developers follow when instrumenting Common Base Event logging in their components.System serviceability architects can use these best practices and techniques to craft a loggingstrategy to ensure consistent and useful problem-determination data to increase systemserviceability and quality.

Note that the Common Base Event model is not associated with a particular consumer, such asa logging facility. This tutorial uses the Java Logging APIs because they provide an integratedand extensible logging facility for the Java language useful for illustrative purposes. However,numerous proprietary and open source logging facilities for the Java language are available. Thetutorial is not intended to be an exhaustive aid in using this or any other logging facility.

Prerequisites

This tutorial is intended for serviceability architects and developers who want to streamlineCommon Base Event logging in new and existing systems written in the Java language. Basicknowledge of generic logging concepts and Common Base Events, and moderate experiencewith the Java language and Eclipse, will help you complete the tutorial's tasks and understand itsexamples.

This tutorial requires the Autonomic Computing Toolkit V3.0.0. The Autonomic Computing ToolkitV3.0.0 requires Eclipse V3.0.3. Eclipse V3.0.3 requires the Java Runtime Environment (JRE)V1.4.x (see Resources).

To run the code and configuration in this tutorial, you need the Common Base Event V1.0.1 Javaimplementation and support in the Log and Trace Analyzer V3.3.0, which is part of the AutonomicComputing Toolkit V3.0.0. Several plug-in Java Archive (JAR) files located in the <AutonomicComputing Toolkit installation directory>\eclipse\plugins directory are required for this tutorial (seeTable 1).

Page 3: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

ibm.com/developerWorks/ developerWorks®

Streamline Common Base Event logging Page 3 of 23

Table 1. Plug-in JAR files required to run the code and configuration in thistutorial

JAR file Plug-in

hlcbe101.jar org.eclipse.hyades.logging.core_3.3.0

hlcore.jar org.eclipse.hyades.logging.core_3.3.0

ecore.jar org.eclipse.emf.ecore_2.0.2\runtime

common.jar org.eclipse.emf.common_2.0.1\runtime

hl14.jar org.eclipse.hyades.logging.java14_3.3.0

hexr.jar org.eclipse.hyades.execution.remote_3.3.0

See Resources or <Autonomic Computing Toolkit installation directory>\eclipse\plugins\org.eclipse.hyades.logging.core_3.3.0\doc.cbe101\index.html for a link to the Common BaseEvent V1.0.1 Java implementation API Javadoc documentation.

Sample code and configuration

This tutorial guides you through streamlining Common Base Event logging instrumentation usingthe Java Logging APIs. The sample code and configuration are provided for reference as anEclipse Java project. The sample code (com.ibm.tutorial.TutorialClass) provides four distinctscenarios, ranging from standard to fully streamlined Common Base Event logging. These fourscenarios illustrate the gradual reduction of complexity and of lines of instrumentation code thatyou can achieve by using the best practices and techniques you'll learn in this tutorial. To make theproject available, follow these steps:

1. Save the Tutorial_Java_Project.zip file to a local directory.2. Start the Autonomic Computing Toolkit.3. Open the Java Perspective by selecting Window > Open Perspective > Other... > Java >

OK.4. Create a new Java project by selecting File > New > Project... > Java > Java Project >

Next.1. Enter a project name, for example Tutorial.2. Select Finish.

5. Import the Tutorial_Java_Project.zip file into the newly created Java project by selecting theproject in the Package Explorer of the Java Perspective and selecting File > Import... > Zipfile > Next.

1. Select Browse... and navigate to the Tutorial_Java_Project.zip file saved in the localdirectory in Step 1.

2. Select the Tutorial_Java_Project.zip file and select Open.3. Select Finish.4. Select Yes in the question dialog.

Figure 1 illustrates the resultant Java project in the Package Explorer of the Java Perspective.

Page 4: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

developerWorks® ibm.com/developerWorks/

Streamline Common Base Event logging Page 4 of 23

Figure 1. Java project in the Package Explorer of the Java Perspective

Problem determination and the Common Base Event modelThis section provides context for this tutorial by reviewing the concept of problem determinationand the Common Base Event model, including the benefits of and concerns with logging eventsand problems in the Common Base Event format. If you are familiar with these concepts, feel freeto skip to the next section, Best practices for Common Base Event logging.

What is problem determination?Problem determination involves detecting, isolating, and resolving run-time problems in computingsystems by monitoring, correlating, and analyzing the system's execution activity. As computingsystems become increasingly complex and fragmented because of the rapid advancements in rawcomputing capabilities and the proliferation of distributed technologies, so does the importance ofmanagement-related activities such as problem determination. For instance, architectures oftenincorporate numerous subsystems, such as servers and databases, and multiple components,such clients and applications, across internal and external networks. Problem determinationis fundamental to the successful and sustainable operation of these complex heterogeneoussystems.

Fortunately, most existing computing systems leverage logging. Logging consists of identifying,capturing, and persisting common events and problems during normal execution. The resulting logdata, or problem-determination data, is often rich in execution-activity and control-flow informationessential for problem determination.

The "problem" with problem-determination dataProblem-determination data often contains varying levels of detail. For instance, log messagesmight correctly describe an event or problem but not its source or context. Furthermore,problem-determination data generated by heterogeneous systems with multiple subsystems andcomponents typically contains vendor-, product-, and version-specific formats and terminology.

Page 5: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

ibm.com/developerWorks/ developerWorks®

Streamline Common Base Event logging Page 5 of 23

For instance, time stamps that denote when an event or problem was captured and logged mightbe represented in varying formats. Also, problem-determination data is often oriented toward aspecific component and not the entire system. Finally, problem-determination data frequently usesvarying natural languages and grammars to describe events and problems. For example, a logmessage denoting a component's initialization might be represented in English as "Component Ahas started" and in French as "Le commencement du component A est accompli" ("The beginningof component A is completed").

The varying detail, terminology, and format of problem-determination data unnecessarilycomplicates problem-determination activities. Deciphering events and problems reported by thesystem's numerous subsystems and components can be challenging and tedious.

The Common Base Event modelThe Common Base Event model seeks to circumvent problem-determination data's varyingformats, terminology, and level of detail. The model provides a standardized taxonomy, unifiedformat, and consistent terminology for encoding events and problems occurring in hardwareand software. A common representation for all events and problems aids in their consistentinterpretation and standardized exchange. For instance, the Common Base Event's timestampproperty -- named creationTime -- is defined as an XML Schema dateTime type, thereby forcingagreement on its format. Furthermore, the model enables the interoperability of problem-determination technologies and tooling -- such as the Autonomic Computing Toolkit -- therebyreducing maintenance costs and increasing system stability, security, availability, resiliency, quality,and asset utilization.

Common Base Events are based on a structured 3-tuple format:

• Situation, including descriptive information• Component that is reporting the situation• Component that is affected by the situation (which can be the same as the component

reporting the situation)

Version 1.0.1 of the Common Base Event model was originally drafted by IBM. The model wassubmitted as a specification to the Eclipse Test and Performance Tool Platform (TPTP) opensource project (formally Hyades) for adoption and implementation. The resulting Common BaseEvent V1.0.1 Java implementation is included in the Log and Trace Analyzer V3.0.0. The modeland implementation are based on open source standards to promote industry-wide acceptanceand adoption.

See Resources for the current Common Base Event specification and an article explaining themodel in greater detail.

Benefits of Common Base Event loggingThe most effective method of capturing vital problem-determination data in a system is CommonBase Event logging. By using the Common Base Event model's standardized taxonomy, unifiedformat, and consistent terminology to encode events and problems, you can circumvent the

Page 6: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

developerWorks® ibm.com/developerWorks/

Streamline Common Base Event logging Page 6 of 23

potential for varying levels of detail, vendor-, product-, and version-specific terminology andformats in problem-determination data. However, you need to create and configure CommonBase Events in close proximity to the represented event or problem to fully leverage the model'sintended benefits. More-detailed and exact information can be captured and persisted in theCommon Base Event when it is created in close proximity to the represented event or problem. Forinstance, situational and contextual information can be extracted directly from the event or problemin conjunction with the pertinent run time configuration and execution information. Creating,configuring, and logging Common Base Events at the source of the event or problem provides thedetailed, exact, standardized, and consistent data required for accelerated problem determinationand increased system serviceability and quality.

Concerns with Common Base Event logging

Complexity and instrumentation code size are common concerns with Common Base Eventlogging. The Common Base Event model was designed to describe all events and problemsabstractly within a system, subsystem, or component, but to be granular enough to describe anyoccurrence of an event or problem. As a result, the model is often considered heavyweight forsimple message logging. Disregarding the tangible serviceability benefits of leveraging the model,the argument is valid. In order for the Common Base Event model to provide a standardizedtaxonomy, unified format, and consistent terminology for encoding all events and problemsoccurring in hardware and software, by definition its design is complex. For instance, the CommonBase Event model defines 12 core situations, each with multiple qualifiers just to define the typeof the event or problem. Beginning users of the model and implementation often experience anelongated learning curve when instrumenting Common Base Event logging.

The complex design of the Common Base Event model directly contributes to increased CommonBase Event logging instrumentation code size compared to alternative, simple message-loggingapproaches. In order to ensure the common representation of all events and problems, theCommon Base Event model enforces several required properties for a Common Base Event andits complex properties. For example, the minimum required fields for a Common Base Event are:

• creationTime• sourceComponentId• situation

Coupled with the additional optional Common Base Event properties, instrumenting code sizecan stretch from 20 to 100 lines of code to create one Common Base Event. Moreover, themodel enforces defined formats for each of its properties to circumvent the varying formats andterminology in problem-determination data. For instance, the Common Base Event's severityproperty captures severity values ranging from 0 to 70. These defined formats also contribute toincreased instrumentation code size when vendor-, product-, and version-specific formats andterminology need to be converted or transformed to the analogous Common Base Event format.

The rather large amount of the instrumentation code required for simple message logging requiresa significant percentage of total code for the system to be dedicated to Common Base Eventlogging instrumentation, resulting in decreased readability and maintainability. Potential adopters

Page 7: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

ibm.com/developerWorks/ developerWorks®

Streamline Common Base Event logging Page 7 of 23

are often discouraged from realizing the tangible serviceability benefits of leveraging CommonBase Event logging.

The rest of this tutorial will provide you with the best practices and techniques required tostreamline Common Base Event logging instrumentation by controlling complexity and decreasingthe lines of instrumentation code. The result will be decreased maintenance and increasedcustomized, vendor-specific content.

Best practices for Common Base Event loggingThe first approach in streamlining Common Base Event logging instrumentation is to use bestpractices. This section examines several best practices for controlling the complexity and size ofcode in Common Base Event logging instrumentation.

Controlling complexityIdentifying core problem-determination data

Core problem-determination data required for systemserviceability and qualitySeveral types of core problem-determination data are required for system serviceability andquality:

• Event time stamps• Event severities and priorities• Component, package, or class name reporting the event• Location of the component, package, or class name reporting the event in a distributed

system• Exception states and stack traces• Descriptive information

A preliminary step in controlling complexity when you instrument an application for CommonBase Event logging is to identify core problem-determination data for the system. Understandingthis data forces you to identify the required activity and control-flow information required in yourlogging instrumentation to accelerate problem determination and increase system serviceabilityand quality.

The core problem-determination data typically consists of the situational and contextualinformation on execution state-change events in conjunction with the relevant run timeconfiguration and execution information. If logging is instrumented in the system, this is a simpleexercise of aggregating the core problem-determination data currently being logged.

Otherwise, the exercise is somewhat more involved, because you must identify and aggregate thecore problem-determination data required for system serviceability and quality. After it's identified,the core problem-determination data provides the necessary foundation for the quantity andcomposition of logging instrumentation. As a best practice, identify the pertinent execution state-change events and aggregate the following information for each event or problem:

• Properties of the problem or event, such as situation, severity, timestamp, and message• Location of the problem or event, such as package, class, and method names

Page 8: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

developerWorks® ibm.com/developerWorks/

Streamline Common Base Event logging Page 8 of 23

• Properties of the run time, such as version, IP address, and thread ID

Mapping properties

After you identify the system's core problem-determination data, the next step in controllingcomplexity is to craft a logical mapping between key properties in the core problem-determinationdata and Common Base Event properties. (An analogous process is followed when you usethe Generic Log Adapter in the Autonomic Computing Toolkit to convert proprietary problem-determination data into the Common Base Event format for use by the Log and Trace Analyzer.The Generic Log Adapter is a rules-based tool that uses a user-provided mapping file, called anadapter, to map proprietary log-data properties to Common Base Event properties.)

In preparation for deriving this logical mapping, consult the numerous resources available tohelp you understand the Common Base Event model (see Resources). Clear and conciseunderstanding of the model will simplify this process and ensure the correct and accurate useof the model. The exercise of exploring the Common Base Event model for properties mostrelevant to the system's core problem-determination data typically shortens the elongated learningcurve often experienced by users of the Common Base Event model and implementation. Thelogical mapping, once finalized, provides a high-level design for the Common Base Event logginginstrumentation.

If Java Logging is currently instrumented in the system, you can write a customized logformatter (extension of the java.util.logging.Formatter class) based on the logical mappingto convert proprietary log records to Common Base Events -- analogous to the formattingsupport in the LTA to convert java.util.logging.LogRecord to Common Base Events (see theorg.eclipse.hyades.logging.java.XmlFormatter class). The existing logging instrumentationsite does not require refactoring to benefit from Common Base Event logging. And the same codecan be used as a generic logging API for the system, thereby reducing the code at the logginginstrumentation site to a single line.

Indentifying static and dynamic data

After you've derived a logical mapping of core problem-determination data to Common BaseEvent properties, identify the static and dynamic data. Static data consists of Common BaseEvent properties that do not change during or between the execution of the system -- for example,run time version, package names, and class names. The static data becomes the focus of thelogging configuration. The next two sections of this tutorial discuss the several best practicesand techniques for dealing with static data using the Common Base Event factory's configurationtemplate.

Conversely, dynamic data consists of Common Base Event properties that are specific to theparticular run time instance of the system, event, or problem -- for example, situation, methodnames, IP addresses, thread IDs, severities, timestamps, and messages. The dynamic databecomes the focus of the actual logging instrumentation code and the Content Handler of theCommon Base Event factory discussed in the following two sections. The division betweenstatic and dynamic data is an important step in preparing to decrease the number of lines ofinstrumentation code.

Page 9: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

ibm.com/developerWorks/ developerWorks®

Streamline Common Base Event logging Page 9 of 23

Decreasing lines of instrumentation code

Regrettably, terse Common Base Event logging instrumentation that fully exploits its intendedserviceability benefits is simply not possible because of the model's elaborate design. Forinstance, 20 lines of code are required to create a Common Base Event with the minimum requiredfields. Unfortunately, there is no silver bullet to achieve both high serviceability and terse logginginstrumentation. However, you can use many best practices and techniques to decrease thelines of code at the actual instrumentation site. Given that high serviceability and terse logginginstrumentation are mutually exclusive, the only recourse is to move lines of code from the actualinstrumentation site to common components and modules, thereby decreasing maintenance andaccommodating vendor-specific content.

Caching recurrent properties

The first approach to decreasing lines of instrumentation code is to cache all recurrent CommonBase Event properties, generic factories, and run time properties that do not change stateduring the system's life cycle. Each property in the Common Base Event logging property cacheis statically initialized for reuse throughout the system. As with all caching strategies, usinga Common Base Event logging property cache promotes decreased memory consumption,increased performance, improved maintenance, and decreased lines of code.

For instance, each Common Base Event instantiated in the system requires a situation propertythat translates into seven to nine lines of code for its creation, configuration, and association withthe Common Base Event. Fortunately, the Common Base Event model identifies a finite numberof core situations -- 12 to be exact -- used to identify the type of events and problems. Cachingthe situations most commonly used in the logging instrumentation reduces the code for settingthese cached situations on the situation property at the instrumentation site to one line. Althoughadditional situation objects for the system's life cycle cause some memory overhead, the reuseof these instances throughout the system results in a decrease of situation objects at any point intime of the system's life cycle.

The Common Base Event logging property cache can also contain generic factories for creatingindividual Common Base Event properties to be reused throughout the system. Common BaseEvents and their complex properties (for example, java.lang.Object) can be created with acached anonymous Event Factory instance resolved from the simple Event Factory Home.Common Base Event properties that do change state during the system's life cycle can also becached for reuse -- for example, a running counter of all logged Common Base Events in thesystem used as the sequenceNumber Common Base Event property. However, complex CommonBase Event properties (for example, java.lang.Object) require cloning by the caller. For example,the msgDataElement property can be cached, cloned, and reused with the applicable msgId,msgCatalogId, and msgCatalogTokens properties set in the instrumentation code.

Finally, you can store pertinent run time proprieties, such as configuration and executioninformation, in the Common Base Event logging property cache. For example, Listing 1 illustratesthe static initialization of the local host's IP address, Report Situation, and Stop Situation.

Page 10: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

developerWorks® ibm.com/developerWorks/

Streamline Common Base Event logging Page 10 of 23

Listing 1. Local host's IP address, Report Situation, and Stop Situationstatically initialized for reuse in the Common Base Event property cache/** * IP address of the local host, otherwise "127.0.0.1". The current IP address * of the local host is assumed to be an IPv4 address. */public static String LOCAL_HOST_IP_ADDRESS = null;

/** * Situation for INTERNAL, SUCCESSFUL, and STOP COMPLETED stopping events. */public static Situation INTERNAL_SUCCESSFUL_STOP_COMPLETED_SITUATION = null;

/** * Situation for INTERNAL and HEARTBEAT reporting events. */public static Situation INTERNAL_HEARTBEAT_REPORT_SITUATION = null;

//Static initialization block:static {

//Resolve the current IP address of the local host: try { LOCAL_HOST_IP_ADDRESS = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException u) { LOCAL_HOST_IP_ADDRESS = "127.0.0.1"; }

//Create and populate an INTERNAL, SUCCESSFUL, and STOP COMPLETED Stop //Situation: INTERNAL_SUCCESSFUL_STOP_COMPLETED_SITUATION = ANONYMOUS_EVENT_FACTORY .createSituation(); INTERNAL_SUCCESSFUL_STOP_COMPLETED_SITUATION.setStopSituation("INTERNAL", "STOP COMPLETED", "SUCCESSFUL");

//Create and populate an INTERNAL and HEARTBEAT Report Situation: INTERNAL_HEARTBEAT_REPORT_SITUATION = ANONYMOUS_EVENT_FACTORY.createSituation(); INTERNAL_HEARTBEAT_REPORT_SITUATION.setReportSituation("INTERNAL", "HEARTBEAT");}

Utility methods in the Common Base EventimplementationThe org.eclipse.hyades.logging.events.cbe.util.EventHelpers classcontains several utility methods to help decrease lines of instrumentation code:

• Conversion between an XML Schema dateTime, a millisecond time stamp, and atextual time stamp

• Conversion of a java.lang.Object to a Common Base Event• Conversion of a java.lang.Throwable to an Extended Data Element• Factory for the values property of an Extended Data Element to ensure that the

1,024-character limit is respected for each index of the array

Leveraging utility methods

Following on the concept of caching all recurrent complex Common Base Event properties, youcan factor recurrent Common Base Event operations out to static utility methods in a CommonBase Event logging utilities class. Often event or problem situational and contextual information,and pertinent run time configuration and execution information, must be converted to a different

Page 11: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

ibm.com/developerWorks/ developerWorks®

Streamline Common Base Event logging Page 11 of 23

format suitable for the Common Base Event model -- for example, converting Java Logging levelsto Common Base Event severities. Furthermore, creating and populating various Common BaseEvent properties can be abstracted to common utility methods. For example, Listing 2 illustrates astatic utility method for creating a Message Data Element using a combination of default propertiesand parameter properties.

Listing 2. Static utility code for creating a Message Data Element using defaultand the parameter properties/** * Static utility method for creating a Message Data Element using default and * the parameter properties. * <p> * * @param msgId * Message ID. * @param msgCatalogId * Message catalog ID. * @param msgCatalogTokens * Message catalog tokens as a String array. * @return */public static MsgDataElement createMsgDataElement(String msgId, String msgCatalogId, String[] msgCatalogTokens) {

MsgDataElement msgDataElement = CommonBaseEventLoggingPropertyCache .ANONYMOUS_EVENT_FACTORY.createMsgDataElement(); msgDataElement.setMsgIdType("IBM4.4.1"); msgDataElement.setMsgCatalog(TutorialClassCatalog.TUTORIAL_CLASS_CATALOG_NAME); msgDataElement.setMsgCatalogType("Java"); msgDataElement.setMsgLocale(Locale.getDefault().getLanguage().concat("-").concat( Locale.getDefault().getCountry())); msgDataElement.setMsgId(msgId); msgDataElement.setMsgCatalogId(msgCatalogId); msgDataElement.setMsgCatalogTokensAsStrings(msgCatalogTokens);

return msgDataElement;}

Periodically, problem-determination data does not cleanly map to one or more CommonBase Event properties. In these cases, the problem-determination data can be mappedto one or more name-type-value properties in the extendedDataElement property. Youcan write such transforms as common utility methods, thereby promoting containmentand reuse. An example is the convertToExtendedDataElement() method in theorg.eclipse.hyades.logging.events.cbe.util.EventHelpers class that converts ajava.lang.Throwable to an Extended Data Element. The Common Base Event V1.0.1 Javaimplementation provides several other static utility methods for a variety of common CommonBase Event operations.

Recurrent logging operations can also be factored out to a static utility method in aCommon Base Event logging utilities class -- for example, instantiating and configuring anorg.eclipse.hyades.logging.java.CommonBaseEventLogRecord. Because the Java Logging APIssupport logging only java.lang.String and java.util.logging.LogRecord log records, the LTAprovides the org.eclipse.hyades.logging.java.CommonBaseEventLogRecord subclass of theproprietary java.util.logging.LogRecord log record required to log a Common Base Event in

Page 12: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

developerWorks® ibm.com/developerWorks/

Streamline Common Base Event logging Page 12 of 23

Java Logging. Because the org.eclipse.hyades.logging.java.CommonBaseEventLogRecord mustbe instantiated with a Common Base Event and configured with a logger's name before beinglogged, factoring this operation out to a static utility method translates three lines of code to asingle line at the instrumentation site.

Using convenience methodsFinally, the Common Base Event V1.0.1 Java implementation provides variousconvenience methods for creating, populating, and setting Common Base Eventproperties based on its parameters. For example, you can set the sourceComponentId andreporterComponentId properties on the Common Base Event by using the setSourceComponentId(String,String,String,String,String,String,String,String,String,String,String) andsetReporterComponentId

(String,String,String,String,String,String,String,String,String,String,String) methods,respectively. Parameters that are null are not set on the property. Although these types ofconvenience methods (for example, method signatures with a large number of parameters) mightdecrease code readability, they do decrease the number of lines of instrumentation code.

Common Base Event factoryThe customizable Common Base Event factory assists significantly in streamlining Common BaseEvent logging instrumentation. After reviewing the architecture of the Common Base Event factory,you'll learn how you can use its reference implementation to populate Common Base Eventsautomatically with static system- and vendor-specific content.

Common Base Event factory architectureThe Common Base Event V1.0.1 Java implementation provides a customizable and extensiblefactory architecture for creating Common Base Events and their complex properties (for example,java.lang.Object). The Common Base Event factory has the standard functionality you'd expectfrom a factory design pattern. However, it also includes a mechanism to populate Common BaseEvents using a customized Content Handler and predefined configuration template.

The configuration template contains Common Base Event properties used to populate theCommon Base Events -- for example, a file containing a Common Base Event represented as asXML fragment. The Content Handler is the in-memory realization of the configuration template. Itmerges the Common Base Event properties defined in the configuration template into a CommonBase Event. The Content Handler can also populate properties on Common Base Events withdynamically resolved run time content, such as the current timestamp.

Because a Common Base Event can be populated by the Content Handler at any time duringtheir life cycle (as discussed below in A layered design), the Content Handler respects existingproperties set on the Common Base Event. All properties set on the Common Base Event atthe instrumentation site have precedence over the properties populated by the Content Handler.The factory is the core mechanism for decreasing the lines of instrumentation code in CommonBase Event logging. All of the static problem-determination data and a subset of the dynamicproblem-determination data identified in the previous section (Best practices for Common

Page 13: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

ibm.com/developerWorks/ developerWorks®

Streamline Common Base Event logging Page 13 of 23

Base Event logging), can be abstracted to the factory's configuration template and ContentHandler. Leveraging the Common Base Event factory results in reduced code size, decreasedmaintenance, and increased customized, vendor-specific content.

A layered designThe factory's design has a layered architecture with four levels of abstraction:

• Event Factory Context• Event Factory Home• Event Factory• Event

The Event Factory Context layer provides an optional look-up service for Event Factory Homesbased on the fully qualified package and class name of the Event Factory Home implementation.This look-up service eliminates the need to import and instantiate typed Event Factory Homesdirectly in instrumentation code but is not required to create an Event Factory Home.

The Event Factory Home layer provides Event Factory instantiation based on a unique factoryname. The Event Factory Home caches named Event Factory instances for added performancewith multiple accesses. Cached Event Factory instances can be updated (for example, by invokingthe updateEventFactory() method) and released from the cache (for example, by invoking thereleaseEventFactory() method) at any time during their life cycle. Event Factory Homes aretightly coupled with a specific type of configuration template used by a specific type of ContentHandler to populate Common Base Events. Event Factory Homes resolve and reload a typedContent Handler based on a typed configuration template from a locatable source. The EventFactory Home and Content Handler are extended to provide run time- and system-specific content,which you'll read about in the next section, Extending the Common Base Event factory. TheContent Handler resolved by the Event Factory Home is set on the instantiated Event Factory forassociation with all newly created Common Base Events.

The Event Factory layer provides a named factory for creating Common Base Events. EventFactories are named using a hierarchical dot-delimited naming convention. As a best practice,factory names should resolve to the component, package, or class name, depending on thegranularity of the configuration template and in line with the system's serviceability initiative. TheEvent Factory associates its Content Handler with each newly created Common Base Event.Moreover, the Event Factory can be configured to automatically populate or complete the newlycreated Common Base Event (for example, invoke the Common Base Event's complete()method). This eliminates the need to invoke the complete() method at the instrumentation site.Although this auto-complete feature has negative performance implications if the Common BaseEvent is never consumed, it eliminates a notable number of lines of code from the instrumentationsite.

Finally, the Event layer is the Common Base Event instance. You can complete Common BaseEvents at any time during their life cycle by invoking the complete() method. This method callsits Content Handler to populate the properties of the Common Base Event. As a best practicefor performance reasons, do not invoke the complete() method until the Common Base Event is

Page 14: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

developerWorks® ibm.com/developerWorks/

Streamline Common Base Event logging Page 14 of 23

about to be consumed or traverse system boundaries (for example, serialized to XML and sentacross a network).

Using the event XML file Event Factory Home

The Common Base Event V1.0.1 Java implementation provides a reference implementation ofboth the Content Handler and the Event Factory Home. The reference implementation of theContent Handler is the Template Content Handler, as defined in the TemplateContentHandlerImplclass. The Template Content Handler uses a Common Base Event instance as the configurationtemplate to complete Common Base Events.

The reference implementation of the Event Factory Home is the event XML file Event FactoryHome, as defined in the EventXMLFileEventFactoryHomeImpl class. The event XML file EventFactory Home resolves and reloads a Template Content Handler based on a template XML fileas the configuration template. The naming convention used for the template XML file is <EventFactory's name>.event.xml.

The template XML file is a well-formed XML document consisting of a single Common BaseEvent XML fragment with one or more defined properties. The XML document conforms to apredefined XML schema (templateEvent.xsd) provided in the Common Base Event V1.0.1 Javaimplementation. You should define in the template XML file the static Common Base Eventproperties identified in the logical mapping of core problem-determination data to CommonBase Event properties. For example, Listing 3 illustrates a template event XML file namedcom.ibm.tutorial.TutorialClass.event.xml with various static properties for the tutorial class.

Listing 3. Template event XML file with various properties set for the tutorialclass<TemplateEvent version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="templateEvent.xsd">

<CommonBaseEvent severity="18" version="1.0.1"> <sourceComponentId executionEnvironment="Java" application="Tutorial" componentIdType="Application" componentType="Java_Application"/> <situation categoryName="ReportSituation"> <situationType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ReportSituation" reasoningScope="INTERNAL" reportCategory="LOG"/> </situation> </CommonBaseEvent></TemplateEvent>

As a best practice, you can define default Common Base Event properties in the template XMLfile. As a consequence, you need to set only nondefault Common Base Event properties on the

Page 15: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

ibm.com/developerWorks/ developerWorks®

Streamline Common Base Event logging Page 15 of 23

Common Base Event at the instrumentation site. For example, the default ReportSituation andseverity properties in Listing 3 are set on all newly created Common Base Events in the Tutorialclass. Leveraging the event XML file Event Factory Home to populate Common Base Events withstatic problem-determination data drastically reduces the lines of instrumentation code, decreasesmaintenance, and increases customized, vendor-specific content.

Resolving the template event XML fileIn order for the event XML file Event Factory Home to resolve the template event XML file, thefile must be accessible by the Event Factory Home's class loader (for example, on the classpath).The event XML file Event Factory Home searches for the template event XML file based on thehierarchical factory name, starting from the full factory name (for example, all segments) anditerating its ancestors to the highest ancestor (for example, first segment). For example, resolvingthe com.ibm.tutorial.TutorialClass Event Factory intern causes the event XML file EventFactory Home to resolve the template event XML file named com.ibm.tutorial.TutorialClass.If this template event XML file cannot be resolved, the event XML file Event Factory Home triesto resolve the template event XML file named com.ibm.tutorial, continuing until com. Templateevent XML files can be specified for any logical grouping of the system (for example, component,package, or class name) in line with its serviceability initiative.

Listing 4 illustrates resolution of an Event Factory from the EventXMLFileEventFactoryHomeImplEvent Factory Home class using the template event XML file in Listing 3 for creating populatedCommon Base Events.

Listing 4. Resolving an Event Factory for creating populated Common BaseEvents/** * Event XML file Event Factory Home to resolve Event Factory instances. */public static EventFactoryHome EVENT_XML_FILE_EVENT_FACTORY_HOME = null;

/** * Event Factory instance for this tutorial class resolved from the event XML * file Event Factory Home. */private static EventFactory eventXMLFileEventFactory = null;

/** * Constant for the fully qualified name (package and class name) of this * tutorial class. */public final static String TUTORIAL_CLASS_NAME = TutorialClass.class.getName();

//Static initialization block:static {

//Retrieve the event XML file Event Factory Home instance from the //singleton instance of the Event Factory Context: EVENT_XML_FILE_EVENT_FACTORY_HOME = EventFactoryContext .getInstance() .getEventFactoryHome( "org.eclipse.hyades.logging.events.cbe.impl.EventXMLFileEventFactoryHomeImpl");

//Resolve the Event Factory instance for this tutorial class //resolved from the event XML file Event Factory Home:

Page 16: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

developerWorks® ibm.com/developerWorks/

Streamline Common Base Event logging Page 16 of 23

eventXMLFileEventFactory = EVENT_XML_FILE_EVENT_FACTORY_HOME .getEventFactory(TUTORIAL_CLASS_NAME);}

Extending the Common Base Event factoryThe extensibility of the Common Base Event factory provides the most effective mechanism forstreamlining Common Base Event logging instrumentation. This section shows how to extend theCommon Base Event factory's Event Factory Home and Content Handler to automatically populateCommon Base Events with dynamic run time- and vendor-specific content from system-specificresources.

Creating a customized Event Factory HomeThe Common Base Event factory provides a customizable and extensible architecture for creatingand populating Common Base Events. Recall from the preceding section (Common Base Eventfactory) that Event Factory Homes are tightly coupled with a specific type of configuration templateused by a specific type of Content Handler to populate Common Base Events. The Event FactoryHome resolves and reloads a typed Content Handler based on a typed configuration template froma locatable source. For example, the event XML file Event Factory Home resolves and reloads aTemplate Content Handler based on a well-formed XML document consisting of a single CommonBase Event XML fragment with one or more defined properties as the configuration template. TheEvent Factory Home can be extended to resolve one or all of the following:

• Customized Content Handler• Specific type of configuration template• Specific location of configuration template

The Common Base Event factory provides an abstract implementation of the Event Factory Home,named org.eclipse.hyades.logging.events.cbe.impl.AbstractEventFactoryHome. The abstractEvent Factory Home is responsible for Event Factory instantiation and caching based on anunique factory name. Cached Event Factory instances can be updated (for example, by invokingthe updateEventFactory() method) and released from the cache (for example, by invoking thereleaseEventFactory() method) at any time during their life cycle. The abstract Event FactoryHome provides the parent or super class for all customized Event Factory Homes. A customizedEvent Factory Home, namely the Log Manager Event Factory Home, extends the abstract EventFactory Home and implements the resolveContentHandler() and createContentHandler(String)methods. For customized Event Factory Homes that do not have an associated typed ContentHandler, both of these methods should simply return null.

Resolving an uninitialized instance of a customized Content HandlerThe createContentHandler(String) method calls the resolveContentHandler() method to resolvean uninitialized instance of the associated typed Content Handler for the customized Event FactoryHome. This method permits extensions of existing Event Factory Homes implementations (forexample, the event XML file Event Factory Home) for associating a customized Content Handlerwith the specific type and location of configuration template resolved by the parent or super EventFactory Home. Moreover, this method can be used to locate and resolve a Content Handler from a

Page 17: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

ibm.com/developerWorks/ developerWorks®

Streamline Common Base Event logging Page 17 of 23

specific location, for instance, using the Java Naming and Directory Interface (JNDI). Conversely,for customized Event Factory Homes that do not resolve a customized Content Handler, thismethod should simply return an uninitialized instance of the Template Content Handler.

The customized Event Factory Home shown in this tutorial is associated with a typed ContentHandler, namely the run time Template Content Handler, as you'll see in Creating a customizedcontent handler. Listing 5 illustrates the customized Event Factory Home resolving an uninitializedinstance of the customized Content Handler.

Listing 5. Resolving an uninitialized instance of the customized ContentHandler/** * @see org.eclipse.hyades.logging.events.cbe.impl.AbstractEventFactoryHome * #resolveContentHandler() */public ContentHandler resolveContentHandler() { return (new RunTimeTemplateContentHandlerImpl());}

The abstract Event Factory Home calls the createContentHandler(String) method to initializethe Content Handler returned from the resolveContentHandler() method. The Content Handler isinitialized from a specific type of configuration template resolved by the customized Event FactoryHome from a specific location. Specifically, this method:

• Resolves the location of the configuration template based on some identifiable marker (forexample, the parameter Event Factory name)

• Retrieves its contents• Configures the Content Handler with the contents of the configuration template using a

common format (for example, Common Base Event object)

For example, the event XML file Event Factory Home's createContentHandler(String) methodinitializes a Template Content Handler returned from its resolveContentHandler() method basedon a well-formed XML document consisting of a single Common Base Event XML fragmentwith one or more defined properties as the configuration template. The configuration template isresolved by searching for the named (<Event Factory's name>.event.xml) template XML file on theclasspath. As you'll learn in Creating a customized Content Handler, the Content Handler then canmerge the contents of the configuration template into a Common Base Event, upon invoking thecomplete() method.

As you know, the core function of a customized Event Factory Home is to resolve a specific type ofconfiguration template from a specific location. Configuration templates can consist of in-memoryCommon Base Event objects resolved using the JNDI and Lightweight Directory Access Protocol(LDAP) or Common Base Event XML documents or fragments resolved from a Web service, HTTPserver, or relational database using Java DataBase Connectivity (JDBC).

One example is retrieving the configuration template from the system's logging facility. Often,systems using the Java Logging APIs configure their logging instrumentation using various key-value pairs in a logging configuration file. The java.util.Properties logging configuration file is

Page 18: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

developerWorks® ibm.com/developerWorks/

Streamline Common Base Event logging Page 18 of 23

loaded by the Java Logging's Log Manager and used to configure loggers, handlers, and the LogManager. Localizing all related logging configuration, including configuration templates, in thesystem's logging configuration file increases serviceability and maintainability.

Adding the configuration template to the logging configuration file

For this tutorial, the template event XML file in Listing 3 is added to the logging configuration file.The name of the template event XML file (for example, com.ibm.tutorial.TutorialClass.event.xml)is the name of the configuration entry. The single Common Base Event XML fragment in the XMLdocument contained in the template event XML file is the value of the configuration entry. Thecustomized Event Factory Home in this tutorial queries the Log Manager using the parameterEvent Factory name and the .event.xml suffix as the name of the logging configuration property.The returned Common Base Event XML fragment is deserialized to a Common Base Event object,used to configure the customized Content Handler.

Recall that the event XML file Event Factory Home permits template event XML files for anylogical grouping of the system (for example, component, package, or class name) by iteratingall hierarchical Event Factory name segments until a configuration template is resolved or allname segments are attempted. The customized Event Factory Home in this tutorial providesanalogous function by continuously querying the Log Manager with all of the hierarchical EventFactory name segments and the .event.xml suffix until the configuration entry is found or all namesegments were attempted. Listing 6 illustrates the customized Event Factory Home initializinga customized Content Handler instance for a named Event Factory based on the configurationtemplate specified in the Log Manager configuration file.

Listing 6. Initializing a customized Content Handler instance for a namedEvent Factory based on the configuration template specified in the LogManager configuration fileif ((factoryName != null) && (factoryName.trim().length() > 0)) {

String parentFactoryName = factoryName; String propertyValue = null; int dotIndex = -1;

while (true) {

//Resolve the configuration template property for this Event Factory //from the Log Manager's properties: propertyValue = LogManager.getLogManager().getProperty( parentFactoryName.concat(".event.xml"));

if (propertyValue != null) {

try {

CommonBaseEvent templateEvent = EventFormatter .eventFromCanonicalXML(propertyValue.trim());

if (templateEvent != null) {

TemplateContentHandler contentHandler = ((TemplateContentHandler) (resolveContentHandler()));

Page 19: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

ibm.com/developerWorks/ developerWorks®

Streamline Common Base Event logging Page 19 of 23

contentHandler.setTemplateEvent(templateEvent);

return contentHandler; } } catch (FormattingException f) { //Ignore since the configuration template property for this Event //Factory is invalid so delegate to the parent factory: } }

//The configuration template property for this Event Factory cannot be //loaded so delegate to the parent Event Factory: dotIndex = parentFactoryName.lastIndexOf('.');

if (dotIndex != -1) { parentFactoryName = parentFactoryName.substring(0, dotIndex); } else { break; } }}

Creating a customized Content HandlerThe Content Handler is the in-memory realization of the configuration template. It merges theproperties defined in the associated configuration template into a Common Base Event. Recall thatthe Template Content Handler uses a Common Base Event instance as the configuration templateto complete Common Base Events. However, the Content Handler can be extended to populateCommon Base Events with dynamically resolved run time content.

Customized Content Handlers provide an effective mechanism for streamlining Common BaseEvent logging instrumentation by automatically populating newly created Common Base Eventswith dynamic problem-determination data, thereby drastically reducing the lines of instrumentationcode, decreasing maintenance, and increasing customized, vendor-specific content. CustomizedContent Handlers can dynamically resolve and populate varying quantities and types of problem-determination data (for example, IP addresses, thread IDs and timestamps) specific to theparticular run time instance of the system, event, or problem without requiring additional lines ofcode at the instrumentation site.

In this tutorial's example, the customized Event Factory Home is associated with a customizedContent Handler, namely the run time Template Content Handler. The customized Content Handleris extended from the Template Content Handler, which uses a Common Base Event instance asthe configuration template to complete Common Base Events. The customized Content Handleroverloads the Template Content Handler's completeEvent(CommonBaseEvent) method to populatethe parameter Common Base Event with dynamically resolved run time content.

After confirming that parameter Common Base Event is not null and has not been previouslycompleted, the completeEvent(CommonBaseEvent) method is invoked on the parent or superclass to merge the Common Base Event properties defined in the configuration templateinto the parameter Common Base Event. This call should appear early in the customizedContent Handler's overloaded completeEvent(CommonBaseEvent) method if the content inthe configuration template has precedence over the properties populated by the ContentHandler. Alternatively, the call can appear later in the customized Content Handler's overloaded

Page 20: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

developerWorks® ibm.com/developerWorks/

Streamline Common Base Event logging Page 20 of 23

completeEvent(CommonBaseEvent) method if the properties populated by the Content Handler haveprecedence over the content in the configuration template.

For the customized Content Handler, the content in the configuration template has precedenceover the properties it populates. Because a Common Base Event can be populated by the ContentHandler at any time during their life cycle, the customized Content Handler must respect existingproperties set on the Common Base Event. Only unset and uninitialized Common Base Eventproperties should be set by the customized Content Handler.

Resolving dynamic problem-determination dataNext, the dynamic problem-determination data resolved at invocation time is set on the parameterCommon Base Event. This data can be resolved at invocation time or retrieved from the CommonBase Event logging property cache. For example, Listing 7 illustrates the customized ContentHandler populating dynamic problem-determination data resolved at invocation time and retrievedfrom the Common Base Event logging property cache.

Listing 7. Resolving and populating dynamic problem-determination databased on the system's runtime instance and the Common Base Event loggingproperty cache//If the global instance ID is not set, assign a new Globally Unique//IDentifier (GUID):if (commonBaseEvent.getGlobalInstanceId() == null) { commonBaseEvent.setGlobalInstanceId(Guid.generate());}

//If the creation time is not set, assign the current time:if (!commonBaseEvent.isSetCreationTime()) { commonBaseEvent.setCreationTimeAsLong(System.currentTimeMillis());}

//If the sequence number is not set, increment the running counter of all//logged Common Base Event and assign the new value:if (!commonBaseEvent.isSetSequenceNumber()) { commonBaseEvent .setSequenceNumber(++CommonBaseEventLoggingPropertyCache.COMMON_BASE_EVENT_COUNT);}

//Retrieve the source component ID://Assumption: The source component ID is not null since it has been//set in the configuration template.ComponentIdentification sourceComponetId = commonBaseEvent.getSourceComponentId();

//If the thread ID is not set, assign the current thread's name:if (sourceComponetId.getThreadId() == null) { sourceComponetId.setThreadId(Thread.currentThread().getName());}

//If the location is not set, assign the local host's IP address and set//the location type to 'IPV4':if (sourceComponetId.getLocation() == null) {

//Set the source component ID's location property to the local host's // IP //address: sourceComponetId .setLocation(CommonBaseEventLoggingPropertyCache.LOCAL_HOST_IP_ADDRESS);

Page 21: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

ibm.com/developerWorks/ developerWorks®

Streamline Common Base Event logging Page 21 of 23

//Set the source component ID's locationType property to 'IPV4': //Assumption: The current IP address of the local host is an IPv4 //address. sourceComponetId.setLocationType(ComponentIdentification.LOCATION_TYPE_IPV4);}

Moreover, the customized Content Handler can resolve dynamic problem-determination datafrom the caller -- typically the logging instrumentation site. For example, Listing 8 illustrates thecustomized Content Handler resolving and populating dynamic problem-determination data basedon the logging instrumentation site.

Listing 8. Resolving and populating dynamic problem-determination databased on the logging instrumentation site//Resolve the current call stack for resolving the caller's class name//and method name://Note: This code handles the three possible call stacks specific to the//tutorial class' programming model.StackTraceElement[] stackTraceElements = new Throwable().getStackTrace();int callersStackTraceElementIndex = 2;String callersClassName = stackTraceElements[callersStackTraceElementIndex] .getClassName();

if (callersClassName .equals("org.eclipse.hyades.logging.events.cbe.impl.EventFactoryImpl")) {

callersStackTraceElementIndex = 3; callersClassName = stackTraceElements[callersStackTraceElementIndex] .getClassName();

if (callersClassName .equals("com.ibm.tutorial.logging.CommonBaseEventLoggingUtilities")) {

callersStackTraceElementIndex = 4; callersClassName = stackTraceElements[callersStackTraceElementIndex] .getClassName(); }}

//Retrieve the source component ID://Assumption: The source component ID is not null since it has been//set in the configuration template.ComponentIdentification sourceComponetId = commonBaseEvent.getSourceComponentId();

//If the component is not set, assign the caller's class name:if (sourceComponetId.getComponent() == null) { sourceComponetId.setComponent(callersClassName);}

//If the sub-component is not set, assign the caller's method name:if (sourceComponetId.getSubComponent() == null) { sourceComponetId .setSubComponent(stackTraceElements[callersStackTraceElementIndex] .getMethodName());}

SummaryConclusionThe Log and Trace Analyzer uses problem-determination data in the Common Base Event format,providing a rich source of activity and control-flow information to accelerate problem determination

Page 22: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

developerWorks® ibm.com/developerWorks/

Streamline Common Base Event logging Page 22 of 23

and increase system serviceability and quality. This tutorial has detailed how to streamlineCommon Base Event logging in the Java language to reduce complexity and instrumentation codesize in order to decrease maintenance and increase customized, vendor-specific content.

The tutorial:

• Reviewed the concept of problem determination and the Common Base Event model• Reviewed the benefits and concerns with Common Base Event logging• Streamlined Common Base Event logging instrumentation using the Java Logging APIs by

leveraging the Common Base Event V1.0.1 Java implementation and support in the LTA• Identified the essential best practices required to control and reduce the complexity of

Common Base Event logging• Extended the Common Base Event factory to reduce the Common Base Event logging

instrumentation code size

Page 23: Streamline Common Base Event logging Before you startconfiguration errors, performance degradation, exception states, resource starvation, security failures, communication delays,

ibm.com/developerWorks/ developerWorks®

Streamline Common Base Event logging Page 23 of 23

Downloadable resources

Description Name SizeSource code for the examples in this tutorial Tutorial_Java_Project.zip 29KB

© Copyright IBM Corporation 2006(www.ibm.com/legal/copytrade.shtml)Trademarks(www.ibm.com/developerworks/ibm/trademarks/)