Receive Application Errors via Yahoo Messenger Blog

    {cs.r.title}



              
                           

    Contents
    Laying the Groundwork
    Writing a CustomAppender in Apache log4j
    jYMSG: The Yahoo Messenger Java API
    Yahoo Messenger log4j CustomAppender
    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. 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 Apachelog4j API. It is expected that the reader knows the following:

    • Configuring log4j vialog4j.properties.
    • Using a standard log4j appender likeConsoleAppender and use of the log4jSimpleLayout class.
    • Using different log4j logging levels likeDEBUG, 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 inlog4j.
    • Usage of jYMSG, a Yahoo Messenger Java API.
    • Writing a Yahoo Messenger instant message customAppender for log4j.
    • Integrating and demonstrating the usage of our customAppender 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 log4jto log a message in the application. This will be our test program. We will be driving log4j by using thelog4j.properties file listed below. In subsequent sections, we will enhance this same properties file. Thelog4j.properties file is shown below:

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

    As seen above, the rootLogger is configured at theINFO level. There is a single Appenderconfigured 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:

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

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

     
    ERROR - Houston! We have a problem! 
    

    Let us now move on to understanding how to write a customAppender 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. Apachelog4j has an abstract class,org.apache.log4j.AppenderSkeleton, that implements most of the functionality needed for writing a customAppender. 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 theLoggingEvent class and perform some appropriate function. Later on, we will see how to extract information from theLoggingEvent class and send a Yahoo instant message.
    • boolean requiresLayout(): This method is used to indicate whether the custom appender requires aLayout. Since we are going to keep things simple, we will simply return false.
    • void close(): This method is called bylog4j 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 aget/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 bylog4j.

    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 thegetMessage() method.

     
    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() {} } 
    

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

     
    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  
    

    If we run the com.oreilly.log4j.yahoo.TestProgramclass again, we will find that our customSampleAppender has started logging.

     
    ERROR - Houston! We have a problem! 
    --> Houston! We have a problem! <-- 
    

    Now that we know how to write a custom appender inlog4j, 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 withlog4j 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 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.

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

    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 Sessionclass belongs to the ymsg.network package of the jYMSG API.
    2. Call the login method of the Sessionobject, 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 Sessionobject.

    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 CustomAppender

    As discussed earlier, we will extend the log4jAppenderSkeleton class and provide the implementation for the three methods, namely append(LoggingEvent),close(), and requiresLayout(). ThisYahooMessengerAppender 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 Appenderneeds 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.
     
    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; } } 
    

    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 andFromYahooIdPassword, 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.

     
    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=  
    
    If we run the TestProgram again, we will receive a Yahoo Messenger instant message, as shown in Figure 1:

    Yahoo IM received via our custom Yahoo log4j <code>Appender</code>
    Figure 1. Yahoo IM received via our custom Yahoolog4j 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 customAppender will be a useful tool in any application deployment scenario, so that support personnel are immediately notified via an instant message.

    Resources

      
    http://today.java.net/im/a.gif