JDK1.4's Java.util.logging package instructions and examples

zhaozj2021-02-16  70

The JDK1.4 released by Sun has added a new core API function for processing application logging in the Java.util.logging package. This Java log package provides a simple and flexible way to embed multi-level logs for Java applications.

brief introduction

java.util.Logging including an Interface: Filter; 15 classes: Logger, LogManager, ErrorManager, Level, LogRecord, LoggingPermission, Handler, MemoryHandler, StreamHandler, ConsoleHandler, FileHandler, SocketHandler, Formatter, SimpleFormatter, XMLFormatter, the following classes are A simple relationship is

Processor inheritance relationship

Handler

MemoryHandler

ConsoleHandler

StreamHandler

FILEHANDLER

SocketHandler

Inheritance relationship of formatting

Formatter

SimpleFormatter

XMLFormatter

Class / interface function summary

1. FILTER: Controlling the output granularity of the log record, the granular range exceeds the function provided by the Level class, set this type in each handler's setfilter method.

2. Logger: In order to utilize a log package, a Logger object, and call a plurality of record methods in the Logger, such as info (String Message). The logger logger creates a logRecord (including the application specific log information) object and pass it to one or more handler, the Handler object outputs it to the target, so that the output of the log record is implemented. During the output of the log, the Logger and Handler objects can determine those logs need to be recorded according to the log level and filter (Filter). At the same time, Handler works with Formatter, formatter formats log information, and determines how log records output to the log.

3. LogManager: Manage a namespace of a log logger object, all named loggingrs are saved in this namespace; manage control properties for logging, these are simple value pairs Like, you can use the Handler and Logging objects for self-configuring;

4. ErrorManager: The ErrorManager object is attached to the Handler object to handle any errors that occur on the Handler object during the log log. But when processing the output log, Handler and There is no callor to an exception to log recorders, but is handled with ERRormanager attached to the handler.

5. Level: Java log package assigns a level to control the output of log messages to each log message. The level is a integer data, the higher the level of records, the greater this integer data. The following level is defined in the Level class (arranged in order from low to high):

level

importance

Log Method

Level value

Severe

Very important

Severe (String Message);

1000

Warning

For warning

Warning (String Message);

900

Info

Information runtime message

Info (String Message);

800

Config

Static setting message

Config (String Message);

700

FINE

Provide tracking information

FINE (String Message);

500

Finer

Display detailed tracking information

Finer (String Message);

400

Finest

More detailed tracking information Finest (String Message);

300

All

Show all information that should log records

Unable

Integer.min_Value

Off

Close log

Unable

Integer.max_Value

6. LogRecord: LogRecord objects are used to pass logging requests between log frameworks and individual logging handler. When a logRecord is passed to the frame, it is logically it belongs to the framework, and should not be applied by the customer. Program use or update

Note: If the client application does not specify a explicit source method name and source class name, when they (Method, or Class) is accessed (because of the call to getSourceMethodName or getSourceClassName method), the LogRecord class will be analyzed. Stack, automatically infer them. Therefore, if a log processor wants to stop passing a logRecord to another thread, or spread through RMI, and if it wanted to get the method and class name, it should call getSourceClassName or getSourceMethodName to make sure that value is filled Into.

7. LoggingPermission: When the code and a security manager that call the logging control method, the security manager will detect this license. There is only one loggingPermission. This value control, And it has the ability to control logging configuration, such as adding or deleting Handler, adding or deleting filters, or changing log levels. Programmers do not have to create a LoggingPermission object directly. But by the security policy file read by the security policy file (Security Policy File) create

8. Handler: Handler object Gets log information from the Logger and outputs it. You may output to the console, or output to the file, or send these log information to the log service in the network, or forward them to the operating system log, or what else. . The JDK1.4 log API provides two Class of Handler objects. MemoryHandler simply saves log messages in a Circular Memory Buffer, which will then publish them to the target handler when a specific trigger event occurs. A typical trigger event is a log message that receives the level that matches the publishing level. If other publishing standards are required, the MemoryHandler class can extends, rewrite the log method to publish memory buffers in accordance with user-defined logging criteria. StreamHandler issues logging to the specified output stream. The Java Log API specifies three streamhandler objects. ConsoleHandler issues logging to the standard error stream. FileHandler Publish logging to the specified file, which can also be configured to write to the loop file set into the log record. SocketHandler issues log records (with other application communication). You can make the processor to be invalid by calling setlevel (level.off), or by calling a suitable level of the Setlevel method. The processor class uses the LogManager property to set the processor filter, format, and level default values. .

9. MemoryHandler: Buffer the request buffer within the memory buffer, usually this processor simply stores the introduced LogRecord in the buffer and discards the previous record. This buffer is cheap and avoids format. In some special circumstances, MemoryHandler will extrude the contents of the current buffer to the target buffer. There are three main models that initiate extrusion buffers:

n The introduced LogRecord has a type greater than the previous definition level, that is, the extrusion level.

N An external class display place call extrusion method

n A subclass overload log method, and scan each introduced LogRecord, if it matches the demand standard, will call the extrusion method

10. StreamHandler: The flow is based on the logging handler, which is mainly used as a base class or support class to implement other logging processors. LogRecord is sent to a given java.io. OutputStream.11. ConsoleHandler: This processor sends logging to the standard error stream (System.err), the default SimpleFormatter is used to generate a short summary

12. FileHandler: Simple file log processor. FileHandler can write a specified file, or a set of loop files. For a set of loop files, when each file reaches a specified size, it will be Close, loop out, a new file is opened. The old file will add "0", "1", "2" in order. The default uses XMLFormatter to format

13. SocketHandler: Publish LogRecord to a network stream connection. Default with XMLFormatter to format

14. Formatter: The formatter provides formatted LogRecord support. Each log processor has a formatter grid. Formatifier gets a logRecord and converts it into a string. Some formats Equipment (eg, XMLFormatter) requires a pack head and tail string around a formatted record. GetHeader and GetTail methods can be used to get these strings.

15. SimpleFormatter: Print A Brief Summary of The LogRecord in a humman readable format. The summary will type, using a simple summary of the LogRecord with a readable format. Typical summary 1 or 2 lines.

16. XMLFormatter: Provides the XML format of the LogRecord formatted tail. DTD specification is available in Appendix A of the Java Logging API APIS specification.

Example analysis

Simple example

This example shows the common operation of Logging

Public class jdk14loggingtest {

/ **

Log recorder

* /

Logger log = logger.getlogger (). Getname ());

/ **

* Log Output Object

* /

Handler FileHandler = NULL;

/ **

* Construction method

* /

Public JDK14LoggingTest () {

// Set the output to the file

Try {

FileHandler = New FileHandler ("% h / java% u.log");

// FileHandler = New FileHandler ("% h / java% u.log", 10, 5, true);

// Set the recording level

FileHandler.Setlevel (Level.warning);

// Set the filter, which has reached a fine particle size record

// FileHandler.Setfilter ();

// Set the output format, there are two types: SimpleFormatter and XMLFormatter,

// The default is XMLFormatter, of course, you can expand, just inherit the formatter class.

FileHandler.SetFormatter (New SimpleFormatter ());

/ / Specify log coding format

// FileHandler.setencoding ("");

// Set the error handling

// FileHandler.SeterrorManager (New ErrorManager ());

}

Catch (Exception EX) {

EX.PrintStackTrace ();

}

Log.addhandler (FileHandler);

Public void testlog () {

GetName ()); GetName ());

Log.log (level.warning, getclass (). getname (), "testlog");

}

Public static void main (String [] args) {

JDK14LoggingTest Test = new jdk14loggingtest ();

Test.testlog ();

}

}

2. Database Handler Example

As can be seen from the above description, JDK1.4's Logging does not provide the Handler that outputs to the database. Here, how to output the log to the database, we know that the Handler object is responsible for getting the log information from the Logger and then outputs it to the destination. . The user wants to store the log into the database, in fact, this is only replaced with the output target of the log information as a database. So write the JDBCHANDLER class that extends the Handler, which is written to the database to the database. To extend the Handler class, you must implement the three abstraction functions of the Handler definition (Abstract):

Public Abstract void flush ();

Public Abstract Void Publish (LogRecord Record);

Public abstract void close () throws java.lang.securityException;

Among them, the Publish (LogRecord Record method is most important, and it finally implements output log information to the target. The close () method is responsible for releasing all the resources owned by Handler. This time we implement log information (package in the LogRecord object) in the Publish (LogRecord Record), you can insert the log information into the database through the appropriate JDBC driver. I will take the log record to the MySQL database output log. The implementation of the complete source code is as follows:

Package com.benqguru.commons.logging.test;

Import java.util.logging. *;

Import java.sql. *;

Class JDBCHANDLER

Extends handler {

Public void flush () {

}

Public void publish (Logrecord Record) {

Connection conn = NULL;

PreparedStatement PSTMT = NULL;

Try {

Class.Forname ("org.gjt.mm.mysql.driver");

CONN = DriverManager.getConnection ("MySQL: //10.89.58.228: 3306 / logtest", "root", "");

IF (conn! = null) {

Object [] Content = Record.getParameters ();

String SQL = "INSERT INTO MyLog (LogTime, EventType" VALUES (?,?)

PSTMT = conn.preparestatement (SQL);

PSTMT.SETLONG (1, Record.getMillis ());

PSTMT.SetString (2, (string) Content [0]);

// Save loginfo in databse

Pstmt.execute ();

}

}

Catch (Exception E) {

E.PrintStackTrace ();

Finally {

IF (conn! = null) {

Try {

CONN.CLOSE ();

}

Catch (Exception EX) {

EX.PrintStackTrace ();

}

}

IF (PSTMT! = null) {

Try {

PSTMT.Close ();

}

Catch (Exception EX) {

EX.PrintStackTrace ();

}

}

}

}

Public void close () throws java.lang.securityException {

}

//testing method

Public static void main (String [] args) {

Logger log = logger.getlogger ("com.benqguru.commons.logging.test.jdbchandler);

JDBCHANDLER JDBC = New JDBCHANDLER ();

Log.AddHandler (JDBC);

String [] content = {"INSERT"};

LogRecord LR = New LogRecord (Level.info, "Second Test Message";

Lr.SetParameters (Content);

// first Insert Log

Log.log (Level.info, "First Mest Message", Content;

// Second Insert Log

Log.log (lr);

}

}

As can be seen from the above code, the program written to the log is not much change. The only thing that needs to be pointed out is that the logging logger is to output the log using the JDBCHandler object you have previously prepared. Specify the JDBCHandler object with the AddHandler method of the Logger object.

reference

Sun

company's

JDK1.4

version

Java.util. Log Logging Package

Source program.

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

New Post(0)