Logging


Many candidates add logging to their application for debugging purposes, so I'll start with this new area of J2SE. The Java logging application programming interfaces (APIs) enable you to produce log reports. You can easily add any information to these reports . Developers often capture status or configuration information to help them eliminate performance bottlenecks and, in particular, bugs .

graphics/tip_icon.gif

You can justify logging in your application because one of the key certification requirements is error handling, one of the original motivations for logging. However, you can also use logging strictly for debugging. If you do, you can either turn it off or remove it before submitting your project. Logging is not specifically required for the certification project, but neither are buttons . If you include logging in your project, you have the option to leave it in your submission (it won't count against you) or to remove it to eliminate the risk of a logging error (for example, can't open a log file).


The approach Sun has taken is to provide a Logger class (think of it as a container) for you to log messages. To log a message, you just dump a message into this container. The Logger class enables you to assign log levels to a message, such as "severe" or " info ." The level indicates a log message's importance, urgency, or priority. If the message you try to log is assigned a level beneath the level that has been set for a Logger object, the message is not logged. You can define your own levels by subclassing the Level class, but you must use a unique integer-level value internally to maintain the uniqueness of your new object, which is necessary for serialization. The predefined levels enable you to filter log messages. For example, the difference between fine, finer, and finest is whether the Logger object filters them out. The levels, in descending priority order, are as follows (if you use these same named constants in code, be sure they are spelled all upper-case ):

  • Severe

  • Warning

  • Info

  • Config

  • Fine

  • Finer

  • Finest

  • All

  • Off

Using a handler, you can tell the Logger class where to store error messages, including file and memory messages (standard error). Although you can write your own error handlers, the following handlers are already in Sun's logging package:

  • MemoryHandler ” Logs are placed in memory.

  • ConsoleHandler ” Logs are sent to System.err.

  • StreamHandler ” Logs are sent to an OutputStream.

  • SocketHandler ” Logs are sent to a remote TCP port.

  • FileHandler ” Logs are sent to a single file or to a set of rotating log files.

Listing 8.1 is a simple program that logs the parameters provided at the command line.

Listing 8.1 An Example of a Logging Routine
 import java.util.logging.Logger; import java.util.logging.FileHandler; import java.util.logging.XMLFormatter; import java.io.IOException; public class MyClass {     public static void main(String[] args)     {         MyClass myClass = new MyClass();         myClass.logParameters(args);     }     public void logParameters(String[] args)     {         Logger myLogger = Logger.getLogger("MyLogger");         // use XML formatter handler         try         {             FileHandler xmlHandler = new FileHandler("log.xml");             xmlHandler.setFormatter(new XMLFormatter());             myLogger.addHandler(xmlHandler);         } catch (IOException e)         {}         // Log the parameters         for( int i = 0; i < args.length; i++)         {             myLogger.warning(args[i]);         }     } } 

If you use the following on the command line

 java MyClass cold strawberry ice-cream cone 

Listing 8.1 sends the following to standard output:

 Mar 13, 2004 9:53:50 PM MyClass logParameters WARNING: cold Mar 13, 2004 9:53:51 PM MyClass logParameters WARNING: strawberry Mar 13, 2004 9:53:51 PM MyClass logParameters WARNING: ice-cream Mar 13, 2004 9:53:51 PM MyClass logParameters WARNING: cone 

Simultaneously, Listing 8.1 produces the following Extensible Markup Language (XML) file:

 <?xml version="1.0" encoding="windows-1252" standalone="no"?> <log> <record>   <date>2004-03-13T21:53:50</date>   <millis>1047621230891</millis>   <sequence>0</sequence>   <logger>MyLogger</logger>   <level>WARNING</level>   <class>MyClass</class>   <method>logParameters</method>   <thread>10</thread>   <message>cold</message> </record> <record>   <date>2004-03-13T21:53:51</date>   <millis>1047621231041</millis>   <sequence>1</sequence>   <logger>MyLogger</logger>   <level>WARNING</level>   <class>MyClass</class>   <method>logParameters</method>   <thread>10</thread>   <message>strawberry</message> </record> <record>   <date>2004-03-13T21:53:51</date>   <millis>1047621231041</millis>   <sequence>2</sequence>   <logger>MyLogger</logger>   <level>WARNING</level>   <class>MyClass</class>   <method>logParameters</method>   <thread>10</thread>   <message>ice-cream</message> </record> <record>   <date>2004-03-13T21:53:51</date>   <millis>1047621231041</millis>   <sequence>3</sequence>   <logger>MyLogger</logger>   <level>WARNING</level>   <class>MyClass</class>   <method>logParameters</method>   <thread>10</thread>   <message>cone</message> </record> </log> 

As you can see, the Logger object automatically provides the date, message sequence (because you instantiated this Logger ), level, class, method, thread, and, finally, the actual message. Logging is clean and simple in J2SE 1.4. You can take advantage of logging especially when you work on the Remote Method Invocation (RMI)/sockets and database portions of your project.

Another interesting feature is the filtering mechanism. If the message passes the filter, it is logged and said to be published; otherwise , it is disregarded. You assign a Filter object to a Logger object by calling the setLoggable (requires a Level to be passed to it) method, which determines whether a log should be recorded or discarded. You must write your own isLoggable method, so it can contain any code you desire , as long as that code returns a boolean. For example, the method could filter on the log length or scan for a keyword. The pseudo code to use a filter looks like so:

 public boolean isLoggable(LogRecord myRecord) {     //do something with myRecord to filter it     // return true to log message or false to ignore it     return false; //conservative default } 


JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 187

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net