HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML

Distributed Logging Using The Java Message Service, by David Chappell & Greg Pavlik

Every software system has logging requirements so application processing can be monitored and tracked. Modern distributed systems, which are usually based on application frameworks, require a logging solution that can cope with multiple processes on multiple hosts sending logging information to a single logging service.

Many application frameworks widely used today, whether they're high-level frameworks like J2EE application servers or low-level frameworks like CORBA ORBs, don't provide a distributed logging facility for application code. Using JMS queues to log application messages is a portable, framework-independent way to efficiently log messages in a distributed system.

Distributed Logging Solutions
It's usually a given that a distributed application needs to keep a centralized application log. We've seen many ad hoc solutions, which are often implemented on a per-application basis. A common way to develop these logging servers is to use low-level APIs, often with the C or Java socket APIs. Logging clients connect by opening a socket and pushing bytes to a log service. Since socket programming is low-level and often error-prone, the logging services are sometimes constructed with an RPC-based distributed object framework such as CORBA or RMI. This provides a higher layer of abstraction to work with, but it still means application developers have to build fundamental application services instead of focusing on the most important task at hand - building real business solutions.

Homegrown distributed logging services are often based on synchronously logging API calls. This means the logging client is forced to block while the logging service processes the message and makes a persistent record in the log. Implementations that support concurrent clients can encounter performance problems related to lock contention in the logging server. In some cases logging services will have internal message queues, so that blocking occurs only through the log message queuing and not throughout the entire logging process. While this approach takes care of the synchronous blocking problem, it's time-consuming and difficult to implement efficiently and reliably, particularly if the solution needs to be coordinated with global or distributed transactions. There are many issues to consider with regard to failure and recovery scenarios for the queue itself and the rules of interaction between the logging client and the logging service under such undesirable conditions.

This matter can be further complicated by geographically dispersed deployments. A distributed application may not be localized to one physical location. Globally distributed applications would presumably need to communicate with the centralized logging system in a secure and reliable fashion over the Internet. As illustrated in Figure 1, you'd likely funnel logging information through intermediate aggregation servers in order to play nice in a firewall environment. These intermediate logging services act as a common conduit that all local applications communicate through. Ideally, these intermediate aggregate servers would be capable of storing log information in case the centralized logging server became temporarily unavailable.

Figure 1

If you were to build a subsystem from scratch that solves all these issues, you'd wind up with something similar to a full-blown JMS queue implementation. Why not use one from the start? It makes perfect sense to base the logging server and its message queue on a common middleware standard and use a common off-the-shelf solution. JMS is an ideal middleware layer that enables distributed logging clients to log messages asynchronously in a uniform and platform-independent way.

It's a natural and pleasant experience to start using JMS to do the same kinds of things that are often done with system-level protocols. JMS has an added advantage as it provides multiple message types for dealing with different kinds of data formats, each with its own set of helper APIs for constructing and deconstructing messages. JMS also accounts for the problems that arise when the intended receivers aren't currently up and running - a crucial advantage for systems that require high reliability and accurate application logging. With JMS, senders and receivers are abstractly decoupled from each other. An application may send a message to an intended receiver, even when the receiver is not available. The JMS system stores messages on the receiver's behalf until the receiver is available. These are important system-level services that would otherwise have to be written by application programmers who could be more productive developing the actual business applications.

In addition, using JMS as the means for a logging mechanism provides the following benefits:

  • Simple, yet flexible standards-based API to be commonly shared among all applications.
  • Nonblocking asynchronous placement of log data into the log queue.
  • Guaranteed once-and-only-once delivery of critical log data to the centralized logging application.
  • Guaranteed ordering of log messages. Messages will automatically be re- ceived by the logging application in the relative order in which they were originally placed in the log queue by the senders.
  • Well-defined messaging models and message delivery semantics.
  • High availability of logging services. Error conditions and the complexities of failure scenarios are handled transparently by the JMS provider or in the interface between the application code and the JMS provider.
As shown in Figure 2, substituting a JMS system as the mechanism for delivering the log data to the centralized logging server removes a great deal of complexity that you would have had to build and manage.

Figure 2

JMS provides support for two messaging paradigms, publish/subscribe and queuing. Publish/subscribe is a broadcast model, which is analogous to an event service. Messages are published to virtual channels called topics and every client registered as a listener for a topic receives the message. Queuing is a point-to-point model. Clients send messages to designated endpoints where messages are enqueued. The message queue is persistent and can be thought of logically as a stack; a message pushed on to a queue will be delivered to a single message consumer. This article uses JMS queues for building application logs.

Logging Queue
Since we're using JMS, the hard work is already done. There's no need to write any infrastructure code at all: JMS provides virtually everything needed for a robust logging service. We need to provide only a logging service implementation that reads the log messages from the queue and does whatever is appropriate for the application. Since the queue is persistent, we don't worry about losing messages. For some JMS implementations, it's necessary to use an administrative console to set up the queue before clients can successfully connect to it. If that's the case, creating an administered object through the console is generally as simple as assigning a name. Self-administered JMS implementations don't require any setup.

Generic Entry Point
To use the queue as a basis for distributed logging, we'll need to define a mechanism for the logging client to write the JMS queue. In general, it's good programming practice to provide a layer of indirection between application code and protocol-specific APIs - the fact that we're using a JMS queue to support distributed logging should be completely transparent. This may be important if you already have a logging subsystem in place.

Migrating each application toward a JMS-based solution can be done separately, obviating the need to coordinate the upgrade of all applications in tandem. In other cases, your application server may provide distributed logging and management capabilities already. Preferably the transport mechanism is dynamically configurable. In Java, this is accomplished with interfaces and Factory classes. Finally, the logging API should be simple and straightforward. Listings 1 and 2 show a simple logging interface and implementation that uses a JMS server to write a log message to a queue. Many applications have more complex log message requirements, so this is an illustrative example.

Access to the client logging implementation is provided by a factory class (see Listing 3).

Log Processing
The logging server may send the data to any number of sources: files, databases, a terminal console, and more. It depends on the specific requirements of the application. In general, simple serialized logging to a file or a terminal console can be accomplished using a JMS MessageListener. The JMS server will automatically serialize messages, eliminating the need for lock management in the logging service code. Listing 4 provides an example of a MessageListener that logs messages to standard err on the terminal screen.

A more complicated logging service might interact with the queue and a database log using global transactions. It might also want to process many messages off the queue concurrently. For these kinds of requirements, an EJB 2.0 message-driven bean may be a more appropriate way to implement the processing logic of the logging service. The EJB container can provide support for global transaction management and concurrent message processing, greatly simplifying the development of the logging service. In addition, the EJB server should provide fault tolerance for the log service itself. In this case, the logging service might have to manage lock contention for writing to log files, but since writing to the log file has been decoupled from application processing by the JMS queue, this doesn't present a performance issue.

J2EE-based applications are hosted by application servers that often run a single logical application in many different virtual machines. This allows the application server to transparently provide scalability and fault tolerance to applications built using J2EE components. Application servers are a perfect use case for a distributed logging facility because the replicated application server instances are all servicing clients of a single application. In most cases it's optimal for the application to use a single log. Servlets and EJBs can simply access a singleton logging client API similar to the one we presented above. JSP developers, on the other hand, shouldn't be forced to write Java code unless it's absolutely necessary. The JSP 1.1 specification provides a facility for writing custom tag extensions. A logging tag could be implemented as shown in Listing 5.

The tag we've defined can be used in a natural way by a JSP developer. Logging to the JMS queue in a JSP becomes as simple as adding a new element to an XML document:

<app:log message="Application successfully processed request." />

Another advantage to using JMS as the basis for distributed logging in a J2EE application is that JMS is a part of J2EE, so a JMS implementation will be provided with the application server. As a practical matter this means a JMS-based logging solution should not incur a large expense.

Beyond J2EE
A J2EE-based application is only one example of a distributed architecture, and J2EE accounts for only a fraction of distributed Java applications. Many Java applications rely on Java RMI or CORBA, directly on JMS, or on a low-level protocol such as Sockets for tying together distributed components. Applications based on any of these protocols and the architectures they suggest can benefit from a distributed log service. All the advantages of building a log service around JMS apply equally well to these applications. Many JMS vendors provide a set of C APIs for their JMS server implementation, which means that JMS can be used as a communication protocol with non-Java applications as well. Thus a JMS-based logging service can be used in a very broad context. It provides a flexible solution for large, heterogeneous enterprise computing environments.

A distributed logging service provides an ideal use-case for JMS. Using JMS, application information can be easily logged to a persistent queue and then processed asynchronously. Application-specific development is pushed to the boundaries of the log processing - time-consuming development of fundamental application services is avoided altogether. JMS also provides fault tolerance and scalability, so the application log can provide highly reliable information. Since EJB 2.0 now integrates JMS into the EJB container, global transactions and support for concurrent message processing can be provided transparently in the logging service.

Authors Bio
Dave Chappell is chief technology evangelist for Progress Software's SonicMQ, and coauthor of O'Reilly's Java Message Service.
[email protected]

Greg Pavlik is a senior architect in HP's application server division.
[email protected]


Listing 1: Interface for the logging client to send messages to a log service 
package util.log; 
 * Title: ClientLog 
 * Description: Interface defining the logging API used by 
   logging clients. 
 * @author Greg Pavlik 
 * @author David Chappell 
public interface ClientLog 
  public void logMessage(String message) throws LogException; 

Listing 2: The JMS-based implementation of the 

ClientLog interface package util.log;
import javax.jms.*; /** * Title: JMSClientLogImpl * Description: Implementation of logging service logging client API; uses JMS * to send the application log. * @author Greg Pavlik * @author David Chappell */ public class JMSClientLogImpl implements ClientLog { /** queue sender for connection */ private QueueSender m_sender = null; /** queue session for connection */ private QueueSession m_session = null; /** * No arg constructor for log service implementation. * Acquire a reference to administered queue via standard * JNDI lookups. * @param initialContextFactory initial context factory * @exception thrown if constructor cannot initialize queue sender */ public JMSClientLogImpl(String initialContextFactory) throws LogException { try { //acquire JMS queue reference via JNDI java.util.Hashtable env = new java.util.Hashtable(); env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); javax.naming.InitialContext context = new javax.naming.InitialContext(env); QueueConnectionFactory qcf = (QueueConnectionFactory) context.lookup("QueueConnectionFactory"); QueueConnection connection = qcf.createQueueConnection(); QueueSession session = connection.createQueueSession (false, QueueSession.AUTO_ACKNOWLEDGE); Queue queue = (Queue)context.lookup("LogQueue"); m_sender = session.createSender(queue); } catch (Exception e) { throw new LogException(e.getMessage()); } } /** * Takes an input string and pushes message on to log queue * @param logEntry the input String */ public void logMessage(String logEntry) throws LogException { try { TextMessage message = m_session.createTextMessage(); message.setText(logEntry); m_sender.send(message); } catch (Exception e) { throw new LogException(e.getMessage()); } } } Listing 3: A factory class for the implementation of the
ClientLog interface package util.log;
/** * Title: ClientLogFactory * Description: Acts as a factory maintaining implementation of ClientLog as a singleton instance. * @author Greg Pavlik * @author David Chappell */ public class ClientLogFactory { /** client log implementation returned by factory */ static private ClientLog m_logImpl = null; static { //hard code for example m_logImpl = new JMSClientLogImpl("JMS Initial Context Factory"); } /** * provides access to singleton instance * @return implementation of ClientLog interface */ static public ClientLog instance() throws LogException { return m_logImpl; } } Listing 4: A message listener that sends text to standard error on
monitoring console package util.log;
/** * Title: LogServiceMessageListener * Description: Message Listener for distributed log example. This example extracts the message text from the message and writes it to standard err. * @author Greg Pavlik * @author David Chappell */ import javax.jms.MessageListener; import javax.jms.Message; import javax.jms.TextMessage; public class LogServiceMessageListener implements MessageListener { /** * Send message contents to standard error * @param message the text message sent from */ public void onMessage(Message message) { try { String text = ((TextMessage)message).getText(); System.err.println(text); } catch(Exception e) { System.err.println("SYSTEM ERROR: could not process message: " + message); } } } Listing 5: A tag extension for JSPs package util.log; /** * Title: LogClientTag * Description: A tag extension for JSPs that uses the ClientLog implementation. * This can be used to send log messages to the JMS queue without * writing any Java code. * @author Greg Pavlik * @author David Chappell */ import javax.servlet.jsp.tagext.TagSupport; public class LogClientTag extends TagSupport { /** Client log message set by JSP engine during tag processing*/ private String m_message = null; /** no arg constructor */ public LogClientTag() { ; } /** * After tag has been encountered, simply send text to ClientLog */ public int doEndTag() throws javax.servlet.jsp.JspException { try { ClientLogFactory.instance().logMessage(m_message); return javax.servlet.jsp.tagext.Tag.SKIP_BODY; } catch (LogException e) { throw new javax.servlet.jsp.JspException(e.getMessage()); } } //ATTRIBUTE ACCESSOR/MUTATORS public void setMessage(String value) { m_message = value; } public String getMessage() { return m_message; } }

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.