Skip to main content

Receive Application Errors via Yahoo Messenger

September 16, 2005

{cs.r.title}









Contents
Laying the Groundwork
Writing a Custom Appender in Apache log4j
jYMSG: The Yahoo Messenger Java API
Yahoo Messenger log4j Custom Appender
Putting It All Together
Conclusion
Resources

Logging application events is a central part of many
applications. Most of our applications do some sort of logging,
using a variety of mechanisms. When things go wrong, the first
course of action is usually to get hold of the application log file
and go through its contents.

Someone supporting live, deployed applications would probably
appreciate the importance of getting notified of application errors
as early as possible. It is much better to be proactive dealing
with errors, rather than waiting to hear from the customer that
something seems to have gone wrong.

How about getting notified immediately, by utilizing an
instant messenger client like Yahoo Messenger?

In this article, we look at integrating application error
logging and instant messenger technology. "http://logging.apache.org">Apache log4j is a widely used
logging API and we will extend log4j to stream our logging events
via Yahoo Messenger. The end result will be receiving a Yahoo
instant message (IM) whenever an error occurs in an application
that you have deployed.

This article assumes familiarity with the Apache log4j API. It is
expected that the reader knows the following:

  • Configuring log4j via log4j.properties.
  • Using a standard log4j appender like
    ConsoleAppender and use of the log4j
    SimpleLayout class.
  • Using different log4j logging levels like DEBUG, INFO, WARN, ERROR,
    and FATAL.
  • Calling basic log4j methods to perform logging.

In this article, we will be covering the following:

  • How to write a custom Appender in log4j.
  • Usage of jYMSG, a
    Yahoo Messenger Java API.
  • Writing a Yahoo Messenger instant message custom Appender for
    log4j.
  • Integrating and demonstrating the usage of our custom Appender
    by getting notification of an application error via a Yahoo instant
    message.

Laying the Groundwork

To get us all started on the same level, we will first write a
small Java program that will make use of Apache log4j to log a
message in the application. This will be our test program. We will
be driving log4j by using the log4j.properties file listed
below. In subsequent sections, we will enhance this same properties
file. The log4j.properties file is shown below:

[prettify]
log4j.rootLogger=INFO,CONSOLE

log4j.appender.CONSOLE=
     org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=INFO
log4j.appender.CONSOLE.layout=
     org.apache.log4j.SimpleLayout
[/prettify]

As seen above, the rootLogger is configured at the
INFO level. There is a single Appender configured called
CONSOLE. This appender utilizes the standard
ConsoleAppender of log4j that prints out the logging
statements to the standard console output. We format the text with
a SimpleLayout, which prints the debug level and the
debug message.

A simple application to put log4j into action is shown
below:

[prettify]
package com.oreilly.log4j.yahoo;

import org.apache.log4j.Logger;

public class TestProgram {
   private static Logger _logger =
            Logger.getLogger(TestProgram.class);

   public static void main(String[] args)
                throws Exception {
   //Simulate the error and log it with
   //the ERROR level
   _logger.error("Houston! We have a problem!");
   }
}
[/prettify]

On compiling and running the above program, we see the following
printed to the standard console:

[prettify]
ERROR - Houston! We have a problem!
[/prettify]

Let us now move on to understanding how to write a custom
Appender in log4j.

Writing a Custom Appender in Apache log4j

Apache log4j provides several appenders that we can use
straight away. It provides appenders that can log to the console, to
a file, to a database, etc. Later on, we will be writing our own
custom Appender that will send a Yahoo instant message. But first,
let us go into the basics of writing a custom Appender in log4j.
Apache log4j has an abstract class,
org.apache.log4j.AppenderSkeleton, that implements
most of the functionality needed for writing a custom Appender. All
we need to do is to extend this class and provide implementations
for the following methods:

  • void append(LoggingEvent): This method will be
    called by log4j at runtime when an output has to occur. We can
    extract the information from the LoggingEvent class
    and perform some appropriate function. Later on, we will see how to
    extract information from the LoggingEvent class and
    send a Yahoo instant message.
  • boolean requiresLayout(): This method is used to
    indicate whether the custom appender requires a
    Layout. Since we are going to keep things simple, we
    will simply return false.
  • void close(): This method is called by log4j
    runtime as a signal to release any resources such as file handles,
    network resources, etc. With no resources to release, we can simply
    keep it empty.

In addition to the above methods, one needs to write a get/set
method pair for each custom property that will be configured for
the appender. The setting of the properties will be done
transparently at runtime by log4j.

Now let us look into writing a simple custom appender based on
what we have learned so far. This appender does nothing useful by
itself, but it serves to illustrate the mechanics and how we can go
about configuring this custom appender. The custom appender behaves
like a ConsoleAppender and outputs the message to the
standard console output. Note that we extracted the information
from the LoggingEvent class by calling the
getMessage() method.

[prettify]
package com.oreilly.log4j.yahoo;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

public class SampleAppender
                    extends AppenderSkeleton {
   protected void append(LoggingEvent event) {
      System.out.println("--> " +
                    event.getMessage() + " <--");
   }

   public boolean requiresLayout() {
       return false;
   }

   public void close() {}
}
[/prettify]

To configure this SampleAppender, we will add the
following lines to the log4j.properties file that we
described earlier.

[prettify]
log4j.rootLogger=INFO,CONSOLE,CUSTOM

log4j.appender.CONSOLE=
     org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=INFO
log4j.appender.CONSOLE.layout=
     org.apache.log4j.SimpleLayout

log4j.appender.CUSTOM=
         com.oreilly.log4j.yahoo.SampleAppender
log4j.appender.CUSTOM.Threshold=INFO


[/prettify]

If we run the com.oreilly.log4j.yahoo.TestProgram
class again, we will find that our custom
SampleAppender has started logging.

[prettify]
ERROR - Houston! We have a problem!
--> Houston! We have a problem! <--
[/prettify]

Now that we know how to write a custom appender in log4j, the
next step obviously is to write a custom appender that will send us
Yahoo Messenger IMs. Before we do that, we need to understand the
Yahoo Messenger Java API that will enable us to do so. Let us move
on, then, to jYMSG, a Java API that allows us to integrate most of
the Yahoo Messenger functionality into our Java programs.

jYMSG: The Yahoo Messenger Java API

Our key objective in this article is to get notified of
application errors via the Yahoo Messenger API. What this means is
that we need to get a Yahoo instant message (Yahoo IM) when there
is an application error. Since we are dealing with log4j and Java,
we need a Java API that allows us to invoke the functionality of
Yahoo Messenger. There are quite a few Java APIs out there in the
open source world that allow us to do exactly this. In this
article, we will be looking at "http://jymsg9.sourceforge.net">jYSMG, a Yahoo Messenger Java
API.

jYSMG is a Java API that allows us to perform common Yahoo
Messenger functions, including:

  • Login and logout from Yahoo Messenger.
  • Send instant message to another Yahoo account.
  • Get status of friends, add/delete/ignore friends, new mail
    notifications, etc.

The above list is just a fraction of Yahoo Messenger's
functionality, and jYMSG does a great job of providing support for
most of it. For the purpose of this article, all we need is the
ability to use a valid Yahoo account to log in, send the IM, and then
log out. Interested readers can explore the jYMSG API for
integrating other Yahoo Messenger functionality into their Java
programs.

We will now write an utility Java class,
YahooMessengerAPI, that will contain a single method,
sendYahooIM. We will be using this class later on,
when we integrate and see the whole thing in action.

[prettify]
package com.oreilly.log4j.yahoo;

import ymsg.network.Session;

public class YahooMessengerAPI {
 public void sendYahooIM(
                     String FromYahooId,
                     String FromYahooIdPassword,
                     String ToYahooId,
                     String msg) {
try {
//Step 1: Create a Session Object
Session _session = new Session();

//Step 2: Login to the From Yahoo Account
_session.login(FromYahooId,FromYahooIdPassword);

//Step 3: Send the Message
_session.sendMessage(ToYahooId,msg);

//Step 4: Logout from the Session
_session.logout();
}
catch (Exception e) {
   System.out.println(e.getMessage()); }
}
}

[/prettify]

The method sendYahooIM requires four parameters. The
first two are the Yahoo account ID and password, which you'll need
to get by creating a new account. The third parameter is the Yahoo
account to which you want to send the IM. This will typically be
the Yahoo ID of the individual who needs to be notified about the
error. The last parameter is a String that contains
the notification message. This contains information about what has
gone wrong in your application. Common information here could
include exception details, a stack trace, etc.

The code works as follows:

  1. Create a Session object. The Session
    class belongs to the ymsg.network package of the jYMSG
    API.
  2. Call the login method of the Session
    object, passing the user ID and password of the Yahoo account from
    which the IM needs to be sent. This could be any valid Yahoo ID and password.
  3. Send the message by calling the sendMessage method
    of the Session object. You need to provide the Yahoo
    ID to which the message is being sent and the message that is being
    sent.
  4. Finally, do a logout on the Session
    object.

We will use this class later on when we integrate write our
custom log4j Appender. Let us now move on to writing our custom
log4j Appender, which will send a Yahoo instant message.

Yahoo Messenger log4j Custom Appender

As discussed earlier, we will extend the log4j
AppenderSkeleton class and provide the
implementation for the three methods, namely
append(LoggingEvent), close(), and
requiresLayout(). This
YahooMessengerAppender is the implementation for our
custom Appender that will send a Yahoo instant message. Note that
in the append method we are using the
YahooMessengerAPI class that we wrote in the previous
section. Additionally, our custom Appender needs several properties
that it uses to send the Yahoo instant message. The properties that
we need are:

  • FromYahooId: This is the user ID of a valid Yahoo
    account from which the instant message is being sent.
  • FromYahooIdPassword: This is the password of the
    above Yahoo account.
  • ToYahooId: This is the user ID of a valid Yahoo
    account to which the instant message is being sent. Typically this
    is the Yahoo account of the individual who would like to be
    notified of any errors.
[prettify]
package com.oreilly.log4j.yahoo;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

public class YahooMessengerAppender
                      extends AppenderSkeleton {

private String fromYahooId;
private String fromYahooIdPassword;
private String toYahooId;

protected void append(LoggingEvent event) {
       new  YahooMessengerAPI().sendYahooIM(
                 getFromYahooId(),
                 getFromYahooIdPassword(),
                 getToYahooId(),
                 (String)event.getMessage());
}

public void close() {}

public boolean requiresLayout() {
       return false;
}

public void setFromYahooId(String fromYahooId) {
       this.fromYahooId = fromYahooId;
}

public String getFromYahooId() {
       return fromYahooId;
}

public void setFromYahooIdPassword(String
                          fromYahooIdPassword) {
 this.fromYahooIdPassword = fromYahooIdPassword;
}

public String getFromYahooIdPassword() {
       return fromYahooIdPassword;
}

public void setToYahooId(String toYahooId) {
       this.toYahooId = toYahooId;
}

public String getToYahooId() {
       return toYahooId;
}

}

[/prettify]

Putting It All Together

To use our custom Yahoo Messenger Appender, we will need to add
it to the log4j.properties file. Shown below in bold are the
relevant entries. Please note that you will have to enter a valid
Yahoo ID and password for the account that will be sending the
notification. The property values that you need to specify are
FromYahooId and FromYahooIdPassword, and
they are commented below. Note that we have also set the
Threshold for the Yahoo Messenger Appender to
ERROR level, so that the instant
message will be sent only if there is an error, as opposed to
lower-severity logging messages.

[prettify]
log4j.rootLogger=INFO,CONSOLE,CUSTOM,YahooMsgr

log4j.appender.CONSOLE=
     org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=INFO
log4j.appender.CONSOLE.layout=
     org.apache.log4j.SimpleLayout

log4j.appender.CUSTOM=
         com.oreilly.log4j.yahoo.SampleAppender
log4j.appender.CUSTOM.Threshold=INFO


log4j.appender.YahooMsgr
 =com.oreilly.log4j.yahoo.YahooMessengerAppender
log4j.appender.YahooMsgr.Threshold=ERROR

# add your username after the =
log4j.appender.YahooMsgr.FromYahooId=
# add your password after the =
log4j.appender.YahooMsgr.FromYahooIdPassword=
# add the account to send the IM to after the =
log4j.appender.YahooMsgr.ToYahooId=

[/prettify]

If we run the TestProgram again, we will receive a
Yahoo Messenger instant message, as shown in Figure 1:

<br "Yahoo IM received via our custom Yahoo log4j Appender" />
Figure 1. Yahoo IM received via our custom Yahoo log4j
Appender

Conclusion

In this article, we learned how to extend log4j by writing our
own custom Appender that sends a Yahoo Messenger instant message
when application errors occur. We also covered the use of jYMSG, a
Java API that lets us integrate Yahoo Messenger functionality
within our Java applications. This custom Appender will be a useful
tool in any application deployment scenario, so that support
personnel are immediately notified via an instant message.

Resources

width="1" height="1" border="0" alt=" " />
Romin Irani is a software architect for InSync Software Inc.