Abnormal and log record

xiaoxiao2021-03-06  106

Abnormal and log record

English original

content:

Start chain abnormal stack access logging full example reference information About the author to this paper

related information:

Logging Toolkit for JavaLogkitjava Exception Handling

In the Java area:

Teaching tools and product code and components all articles practical skills

Use J2SE's useful changes to eradicate problems and appropriately respond to John Zukowski (Jaz@zukowski.net) president, JZ Ventures Company December 2001

In order to understand the roots of the problem and respond appropriately, the Merlin release has added several features related to exception handling. Now, you don't have to manually analyze the stack dump information, you can check the stack tracking information, and you can connect an exception into a daisy chain, which will greatly promote debugging work. In addition, there is a built-in logging tool to record different levels of messages. in

This part of Merlin's magic series, John Zukowski demonstrates the working principle of these new logging and exception functions and provides an example program for viewing and download.

Many of this Merlin distribution (such as exception handling and logging feature) are not as exciting as other features, but they are useful and worthy of our concern. All Java developers should be familiar with the basic structure of performing exception processing: put the code that may throw an exception in the TRY block, then, in this block, it has thus thus, then the Catch under this block. Swords to process. This basic structure does not change in this Merlin release. The new feature in the release version 1.4 is if an exception is thrown from the Catch clause, you can attach the initial reason for this exception. This is really a trick that is easy to debug! Also, if you want to record where the exception occurs, you don't have to manually analyze the stack tracking information. It is now supported through the program to access the stack tracking data, and there is a "logging API" (Logging API) is used to record this data (or any other content). Here is a list of new features we have to discuss this month:

The chain abnormal tool uses the program's way to track the basic programs in the API Start Listing 1 contain three methods, which can throw an exception. Each exception is processed by displaying a message. In the first example, the abnormality is reappeared to display a second message for the problem. Listing 1. Ovenger handling skeleton program

Import java.io. *;

Public class exceptions {

Private static void fileAccess () throws oException {

// Fails Because Prefix Is Too Short

File f = file.createTempFile ("x", "y");

}

Private static void divzero () {

System.out.println (1/0);

}

Private static void arrayAccess (string array []) {

System.out.println ("First:" Array [0]);

}

Public static void main (string args []) {

Try {

Try {

FileAccess ();

} catch (exception e) {

System.err.Println ("prefix too short");

Throw e;

}

} catch (exception cause) {

System.err.Println ("Cause:" Cause);

}

Try {

Divzero ();

} catch (exception e) {

System.err.Println ("Division By Zero");

E.PrintStackTrace ();

}

Try {

ArrayAccess (ARGS);

} catch (exception e) {

System.err.Println ("No Command Line Args");

}

}

}

Chain abnormal a chain exception is an exception, which allows you to attach a "cause" anomaly to an exception being thrown. In essence, you are creating an abnormal chrysanthemum chain. For example, when you throw (and capture) your custom anomalies, you can say that the reason for this exception is an I / O exception. Support chain exception starts from the Java.lang.Throwable class class. Now, there is only two constructor (one of which no parameters, the other accepts a detailed message as a parameter), but there are four constructor:

Throwable () Throwable (Throwable Cause) Throwable (String Message, Throwable Cause) When you create your own exception type, you should additionally add two constructor. In that, you can easily deliver the cause of this anomalies when you are created. You can still link them even if you don't change your Exception subclass. This method only requires you to call the INITCAUSE (Throwable Cause) method of your subclasses. To present the link, Listing 2 should replace the first two TRY blocks in the Exceptions class. It defines a custom anomalous class (at the same time), and throws this custom anomalous class rather than the fileAccess () exception processing: Listing 2. Chain exception code

Try {

Try {

FileAccess ();

} catch (exception e) {

Class theexception extends Exception {

Public theexception () {

}

Public theexception (String Message) {

SUPER (Message);

}

Public theexception (throwable throwable) {

Super (throwable);

}

Public Theexception (String Message, Throwable throwable) {

SUPER (Message, Throwable);

}

}

Theexception theexc = New theexception ("Prefix Too Short", E);

Throw theexc;

}

} catch (exception cause) {

System.err.Println ("Cause:" Cause);

System.err.println ("Originalcause:" Cause.getcause ());

}

Stack Access Now, we will add a little complex by accessing exception stack tracking information. As shown in the second method call in Listing 2, printStackTrace () can be called to display the stack dump information of the call sequence to throw an exception line. The PrintStackTrace () method can accept the PrintStream or PrintWriter as a parameter, and if it is not available to the method, it will send the output to System.err. If you want to display the stack tracking information in your own format, instead of dump in the default format, you can call the getStackTrace () method, which will return a StackTraceEleMent object array. You can find many different features of each element: getFileName () getFileName () getMethodName () isnativeMethod () By calling different methods of each element, you can use any favorite format to display stack dump information . Replacing the PrintStackTrace () call will display the file name, line number, and method name of each stack element. Listing 3. Manually display stack tracking information

StackTraceElement Elements [] = E.GETSTACKTRACE ();

For (int i = 0, n = elements.length; i

System.err.println (Elements [i] .GetFileName () ":"

Elements [i] .getlinenumber () "==>"

Elements [i] .getMethodName () ');

}

One point to pay attention: The first element of the array (not the last element) is the top of this call tracked. Logging does not want to send the stack tracking information to System.err, you can use the logging tool for the Java platform provided in the new java.util.logging package. Although there are many configuration options available through XML and filtration, the basic structure is required to obtain a logger object and use a general log (Level Level, String Message) method to log logging, or call the method for special log levels (such as Fine) ()). There are seven different levels, plus two points indicating "all" or "no":

Severe Warning Info Config Fine Finer Fine Finest All None Listing 4 Adds a logging feature to the third TRY block, only logging that the stack tracks each part of the method name. Listing 4. Basic log recorder usage

System.err.Println ("No Command Line Args");

Logger logger = logger.getlogger ("Net.zukowski.ibm);

StackTraceElement Elements [] = E.GETSTACKTRACE ();

For (int i = 0, n = elements.length; i

Logger.log (Level.warning, Elements [i] .getMethodName ());

}

By default, logging messages are sent to the console. You can add a logging to a file by adding a handler to LogManager, as shown in Listing 5. Listing 5. Add log record to files

Try {

Logmanager Manager = logmanager.getlogmanager (); handler handler = new filehandler ("zuk.log");

Manager.addglobalhandler (Handler);

// log it

} catch (ioexception logException) {

System.err.Println ("Logging Error");

}

When the console output format is not an easy-to-analyze format, the file output is stored as an XML document. Listing 6 shows this output of this example. Listing 6. Sample log file output

2001-10-30T16: 24: 23

1004563463843

0

Net.zukowski.ibm

Warning

Exceptions

Main

10

ArrayAccess

2001-10-30T16: 24: 24

1004563464015

1

Net.zukowski.ibm

Warning

Exceptions

Main

10

main

Complete Example Listing 7 provides a complete example for you to test these new features. Listing 7. Complete example

Import java.io. *;

Import java.util.logging. *;

Public class exceptions {

Private static void fileAccess () throws oException {

// Fails Because Prefix Is Too Short

File f = file.createTempFile ("x", "y");

}

Private static void divzero () {

System.out.println (1/0);

}

Private static void arrayAccess (string array []) {

System.out.println ("First:" Array [0]);

}

Public static void main (string args []) {

Try {

Try {fileAccess ();

} catch (exception e) {

Class theexception extends Exception {

Public theexception () {

}

Public theexception (String Message) {

SUPER (Message);

}

Public theexception (throwable throwable) {

Super (throwable);

}

Public Theexception (String Message, Throwable throwable) {

SUPER (Message, Throwable);

}

}

Theexception theexc = New theexception ("Prefix Too Short", E);

Throw theexc;

}

} catch (exception cause) {

System.err.Println ("Cause:" Cause);

System.err.println ("Originalcause:" Cause.getcause ());

}

Try {

Divzero ();

} catch (exception e) {

System.err.Println ("Division By Zero");

StackTraceElement Elements [] = E.GETSTACKTRACE ();

For (int i = 0, n = elements.length; i

System.err.println (Elements [i] .GetFileName () ":"

Elements [i] .getlinenumber () "==>"

Elements [i] .getMethodName () ');

}

}

Try {

ArrayAccess (ARGS);

} catch (exception e) {

System.err.Println ("No Command Line Args");

Try {

Logmanager manager = logmanager.getlogmanager ();

Handler Handler = New FileHandler ("Zuk.log");

Manager.addglobalhandler (Handler);

Logger logger = logger.getlogger ("Net.zukowski.ibm);

StackTraceElement Elements [] = E.GETSTACKTRACE ();

For (int i = 0, n = elements.length; i

Logger.log (Level.warning, Elements [i] .getMethodName ());

}

} catch (ioexception logException) {

System.err.Println ("Logging Error");

}

}

}

}

Reference

Please participate in the discussion forum of this article. The Chained Exception Facility Overview describes the exception link and stack tracking access. Java Logging overview demonstrates many other features available for new logging tools. How to use it through Javadoc through the logging tool. IBM AlphaWorks's Logging Toolkit for Java offers an excellent, earlier than Merlin logging tool. The developerWorks Web service area provides Logkit as a recommendation component of "One Week Components" (August 2001). A senior software engineer with PETER HAGGAR, IBM offers slide demonstrations on Java Exception Handling (DeveloperWorks, March 1998). Please read the full discipline of Merlin skills written by John Zukowski. Please find more Java reference materials on the developerWorks Java Technology area. About the author John Zukowski is engaged in strategic Java advice through JZ Ventures, as well as resident guidelines for JGuru's Java-driven Java-driven Java. His nearest work has Apress published Java Collections and Definitive Guide to Swing For Java 2 (2nd Edition). You can contact him through jaz@zukowski.net.

Http://www-900.ibm.com/developerWorks/cn/java/j-merlin/index8.shtml

转载请注明原文地址:https://www.9cbs.com/read-104612.html

New Post(0)