Friday, October 23, 2009

Intercepting Log Messages in Glassfish

TOKYO - JULY 22:  In this handout image provid...Image by Getty Images via Daylife

I wanted a way to capture certain types of errors from an OpenESB application, under the Glassfish application server. I had to do this because a couple of error scenarios get their exceptions handled at a lower level than my application code and I never get a chance to detect the problem. One approach to resolving this is to write some completely external process to monitor the log file itself. But a another way is to use Glassfish's Self-Management Framework, an MBean and a rule.

There weren't a lot of examples of this to be found, so here some code. First, the MBean itself. The MBean needs to be built in conformance with some simple but very specific rules.
  • It must implement javax.management.NotificationListener
  • It must have an interface of its own with the same name as the MBean, but ending in "MBean"
Here is the MBean interface:
package com.log.monitor;

import javax.management.Notification;
import javax.management.NotificationListener;

public interface CustomActionMBean {
public int getA();
public void setA(int a);
}

It is a trivial Java Bean interface with one getter/setter pair added here just as an example. Here is the implementation class:
package com.log.monitor;

import javax.management.Notification;
import javax.management.NotificationListener;

public class CustomAction implements CustomActionMBean, NotificationListener {
private int a = 0;

public CustomAction() {
}

public void setA(int a) {
this.a = a;
}

public int getA() {
return a;
}

public void handleNotification(Notification arg0, Object arg1) {
System.out.println("Called... " + arg0.getMessage());
}
}
These get built into a jar file called CutomAction.jar, using whatever IDE or command line you prefer. I used Eclipse, and I found that I had to uncheck the compression option to get this to fully work.

I deployed the jar file to Glassfish using its web-based administration console. This is done in a manner simular to deploying anything else, but using the section under "custom mbeans." There is a command line method too, using asadmin. The deployment will fail if there's anything wrong with the MBean, such as an incorrect interface name or referring to the wrong Notification classes.

Once this is done, a Management Rule can be created. The key here is that the "event type" should be "log". The MBean deployed above should appear in the "Action" drop down list. Each event type has different options. In the case of a log type it is also possible to select a log level, and a specific logger as filters. But once activated, this rule will call the new MBean as needed when an appropriate log message is created. The raw message string is available from the Notification object with getMessage().

Here's a few good resources on all this:

http://weblogs.java.net/blog/sankara/archive/2006/02/self_management.html


http://blogs.sun.com/technical/entry/self_management_rules


https://glassfish.dev.java.net/javaee5/selfmanagement/selfmanagementhome.html


http://www.caucho.com/resin-3.0/jmx/tutorial/listener/index.xtp
Reblog this post [with Zemanta]

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.

Jeff Sexton

007 1:144 Scale 1:350 Enterprise 10 Barrel Brewing 14 1856 2001 A Space Odyssey 3D modeling 40and20 4th of July 78 RPM Abyss Adam West Advertising Agora Models Air Canada Airline Airways Brewing Alan Bennett Alaska Alberta Alberta Street Pub Alfa Romeo Spider Touring Gran Sport Amati Amazon Amnesia Brewing AMT Analog signal Android Anomalies and Alternative Science Antiques Apache Apollo Apple Apple Stores Art Artisanal Beer Works Assembly Brewing Aston Martin Astoria Asus Atlas Audrey Augmented reality Aurora Famous Fighters auto-awesome Automobile Autos Aviary Aviation Backups Baelic Brewing Bale Breaker Brewing Bandai Barack Obama Barley Brown's Beer Bars Base Camp Brewing Batman Battery Beards Beer Beer Bar Bell System Bellwether Berkshire Hathaway Betty White Beyond the Fringe Bigfoot Bikes Bill Clinton Bird Food Bird Toys Birds Birthdays Bleriot Bleriot XI Block 15 Brewing Blogger Bojack Horseman Bolton Landing Brewing Boltons Boneyard Brewing Books Boxer Ramen Boxer Ramon Breakside Brewing Brian Eno Build Management Buoy Brewing Burger King Business and Economy Business Process Execution Language Bye & Bye Byte-order mark Canadian Carrot Cats Chex Mix Chihuly Chipmonk Christmas Civil Defense Clinton Clocks Closet Doors CNN Cockatiels Cocktails Collections Columbia Grafonola Columbia River George Columbia River Gorge Corners Corvallis County Cork Crooked Stave Brewing Crows Crux Brewing Cuisinart Culmination Brewing David Byne DB5 Dear Jane Debian Deschutes Brewing DFW C.V Diabetes Dick Curtis Digital Living Network Alliance Digital television Dinosaurs Disney Doll House Don the Beachcomber Double Mountain Brewing Dow Jones Industrial Average Dragons Dudley Moore Duesenburg SJ Roadster Durham University DVD E-mail address E9 Eagle Eagle Creek Fire Eaglemoss Easter ebauche Ecliptic Economics Ed Ed and Olive Eels EJB Elgin Elysian Brewing Energy development Enterprise Enterprise JavaBean ESP Evergreen Air Museum Everybody's Brewing Ex Novo Brewing F-84G Thunderjet Facebook Family Photos Fathers Day Fearless Brewing Fedora Ferment Brewing Ferns Festival of The Dark Arts Filesharing Finance Finger Firesign Theater Fireworks Flowers Flying Sub Food Ford Fort George Brewing Fossil fuel Free House Garfield James Abram Garfield Minus Garfield Gateway Brewing Gene Sexton Gene Wilder George Carlin Gigantic Brewing Gilgamesh Brewing Glass Glassfish Global warming Golden Arches Goldfinger Goofy Google Google Assistant Google Buzz Google Docs Google Home Google Lively Google Photos Google Reader Google Wave Google+ Goose Graffiti Grammar Gravy Great Divide Brewing Great Notion Brewing Greek Festival Greenhouse gas Gruen GT40 H. G. Wells Half-Life 2 Halloween Harlan Hawaii Helbros High-definition television Hilo Hilo Brewing History Ho 229 Hollywood Theater Hopworks Urban Brewery Horizon Models HP Hybrid electric vehicle IBM Impala Inner city Instagram Insulin Investing IPMS Iris Irony J.C. Penny James Bond Jane Austen Java Java Architecture for XML Binding JC Penny JDBC Jeannine Stahltaube Jeff's! Jim Davis joe the plumber John McCain Jonathan Miller Jubelale Kapaau Karma Kauai Kay Thompson Kermit the Frog Keys Keys Lounge Kids and Teens Kona LA Auto Show Labrewtory Larry King Laser Laserdisc Leavenworth Wenatchee River Level Brewing Lilly Tomlin linux Little Beast Brewing Lloyd Center Logging Lowry Sexton LPs Lucky Lab Magnets Mark Cuban Market trends Martin Mull Maytag McDonald Mediatomb Meier and Frank Mel Brooks Mercury Microsoft Microsoft Windows Migration Brewing Mobius Models modern Times Brewing Money Monkey monsters Moon MOUNT HOOD Mount Tabor Movie Reviews Multnomah Falls Music Music industry Muxtape MySQL NetBeans Netflix Nikon Nikon Z50 Ninkasi Brewing Nintendo Nissan Cube Norm Coleman North Bar Nuclear fallout Nuclear warfare Nuggest Nuts OBF Office Depot Offshoot Beer Co Oktoberfest Ola Brewing Old Town Brewing Olive Open ESB Oracle Corporation Orca Oregon Orion Space Clipper Otto Owls Pacific Ocean Packard Boattail Pam American Parrots Patio Sale PDX Pearl District Pearl District Portland Oregon Peppers Performance Review Peter Cook Peter Iredale Pets Pfriem Brewing Philip K Dick Phone Book photography Pizza Plank Town Brewing Play Station PlayStation 3 pluspora Pocher Podcast Poke Pokémon HeartGold and SoulSilver Polar Lights Politics Pono Brewing Portal Portland Portland Development Commission Presidents Pride and Prejudice Programming Projects PS3 PS4 Pumpkins Quotation Marks Rad Power Radio Radio Room Ramen Ramon Recipes Recording Industry Association of America Renewable energy Reservoir Reuben's Brewing Reubens Brewing RIAA Richmond Pub Robot Chicken Rock-paper-scissors Rogue Brewing Round 2 Sales San Francisco Santa Sarcasm Sasquatch Brewing SATA Science fiction film Sea Quake Brewing Seattle Selfie Serbia Service-oriented architecture Seward Shelby Cobra Shipwreck Shopping Signs Silver Moon Brewing Slide Rule Snow Soap Soap Cutter Social Security Social Studies Society6 Sony Sopwith F.1 Camel BR.1 Soviet Space 1999 Space Race Spad XIII Speaker Repair Spirit of St. Louis Spitfire SQL Squirrel's St Patricks Day Stanford Hospital Star Trek Star Wars Starbucks Stock market Storm Breaker Strip search Stripes Studebaker Studellac Sun Microsystems Supernatural T-Mobile Tablet Tamiya Tamiya Spitfire Taube TechCrunch Technical Television Terminal Gravity Thanksgiving The Producers ThinkGeek Three Creeks Brewing Thunder Island Brewing Tiki Time Bandits Toaster Tom Peterson Tools Top Ferment Total Recall Transportation Security Administration Trumpeter Tubboat Tyco UFOs Unicode United States United States Department of Homeland Security Universal Plug and Play Unknown Primates USB USS Yorktown Valcom Van Gilder Hotel Vegetable garden VHS Victoria Video Video game Vintage Images Vintage Vintage! Virtual world Volcano Hawaii Volvo C70 Voyage to the Bottom of the Sea Wall Street War of the Worlds Warren Buffett Warrenton watches Watercolor Wayfinder Brewing We Can Remember It for You Wholesale Web service Web Services Description Language Whiskey Wii Windows 7 Windows Phone 7 Windows Vista Windows XP Windy Wingnut Wings Wood Worthy Brewing WWI WWII X-Files X-ray vision XML XML Schema Y2K Yeti YouTube Yugo Zero Mostel Zima Zoom H2n