Log facility and general implementation

Source: Internet
Author: User
Log facility and general implementation

 

Eternal life (gongys@legend.com ),

 

Introduction:This article describes in detail commons-logging, one of the Jakarta projects ). In order to give you a clear and comprehensive understanding of general log implementations, This article focuses on two major parts: The first part describes the vision, user value, and functional features of the log facility, the second part describes general implementation. In the second part, we will first describe how to use universal implementation (the reader can get an intuitive feeling from here), and then describe the internal design of universal implementation, then, in the left-over question Section, the general implementation of relatively complete log facilities is not perfect. The first part raises the problem and the second part solves the problem. The last part is the conclusion, mainly for the reader's use suggestions and design suggestions.

Label of this article:_ Unassigned

 

Mark this article!

 

Release date:June 01, 2003
Level:Elementary
Access status168 views
Suggestion:0 (Add Comment)

Average score (0 in total)

 

1. Preface

This article introduces one of the Jakarta projects.commons-logging(General log implementation ). In order to give you a clear and comprehensive understanding of general log implementations, This article focuses on two major parts: The first part describes the vision, user value, and functional features of the log facility, the second part describes general implementation. In the second part, we will first describe how to use universal implementation (the reader can get an intuitive feeling from here), and then describe the internal design of universal implementation, then, in the left-over question Section, the general implementation of relatively complete log facilities is not perfect. The first part raises the problem and the second part solves the problem. The last part is the conclusion, mainly for the reader's use suggestions and design suggestions.

This is the first article in the series of open-source projects. The author organizes the ideas in the following articles and calls this idea "Open-Source Project Description Framework ":

  1. Preface-purpose of describing the article
  2. Project vision: Describe the ambitious objectives of the project that the author understands;
  3. User problems-describes the potential user values of a project;
  4. Simple analysis-used to describe the features of a project product driven by user issues;
  5. User Interface-used to describe how to use the project product. Some simple examples are provided to describe the application programming interface and static configuration interface;
  6. Internal profiling-describes the source code usage mode and best design practices of the project;
  7. Legacy issues-used to describe the future development direction of the project products;
  8. Summary: It is used to describe the use suggestions and design suggestions for readers.

Back to Top

2. Project VISION

Provides a ready-made, well-defined, and scalable Log facility for software development. The so-called "ready-made" means that software development can be used immediately, including API documentation, use instances and libraries; "well-defined" means that the project provides good interfaces for use and has excellent internal design; scalability means that users can further expand their functions.

Back to Top

3. User Problems

There are three types of users who care about software logs: developers, system administrators, and system operation units. Three types of users have different log Requirements:

  • When writing code, developers often need to output the internal state of the program, which can be debugging during development or maintenance during running.
  • System administrators need to obtain software status data to further configure the system for normal and efficient operation.
  • The operating unit of the system needs the software to save the operation log for routine check or accounting.

Back to Top

4. Simple Analysis

Although each of the three types of users has its own needs, the Log facility can be attributed to the following features:

  1. Log operations
    The log function is a basic log registration operation and a simple interface between the software system and the Log facility. Generally, software systems only transmit Application log information to these functions.
  2. Level

    Level indicates that the software system can register logs in different levels. The level features of the log facility are shown in two parts: log operation and facility configuration. The log operation level indicates that the software system can specify a log registration level. The level of facility configuration specifies the lowest level of valid log operations. If a log operation level in the software system is lower than the configured level, this log operation is invalid and no log registration is performed.

    The level of log facilities is very useful for developers. On the one hand, it helps developers understand detailed system status information during system tuning, on the other hand, it helps developers diagnose and solve software system faults during operation. In addition, when the system changes from the development status to the running status, the debugging log code inserted to the software by the developer does not need to be deleted. Instead, you only need to increase the log configuration level and finally enable the programmer. out. println has become a hobby.

  3. Log target diversity

    The diversity of log targets means that logs can be registered to devices on multiple days, such as files, consoles, databases, and email systems.

    The diversity of log targets allows the software system to output logs to different devices according to certain standards. For example, debugging logs can generally be output to the console, and routine inspection logs can be saved to the database, logs of system errors can be sent to the administrator or maintainer's email address through the email system.

  4. Log format

    As a facility, in addition to registering the application log information specified by the software system, the logging facility often provides additional system log information, such as the system time and log context, all log information can also be formatted.

    The log format is generally set in the configuration file of the log facility, which helps reduce the programming burden when the software system calls the log operation interface and reduce the complexity of the interface.

    It is worth noting that the software system records something in the log device. That is to say, the specific content of the application log information is determined by the software system using the Log facility and has no direct relationship with the Log facility.

Back to Top

5. Common-logging user interface

The user interface consists of a programming interface and a configuration interface. The programming interface describes how to use the Log facility in the software system to register logs and configure the interface to plan the operation of the log facility.

5.1 Overview

The log levels of common-logging can be trace, debug, info, warn, error, and fatal, from low to high. Its level is reflected in the programming interface and in the configuration interface.

Common-logging is a common log encapsulation. It can be encapsulated by specific log systems such as log4j, logkit, and logs in jsdk 1.4. In the running stage, the binding mainly depends on the configuration interface and the binding search policy of common-logging.

Log format. The diversity of log targets depends on the capabilities and configurations of specific log systems.

5.2 Application Programming Interface

The Application Programming Interface of common-logging is defined mainly in the org. Apache. commons. Logging. Log interface. This interface mainly defines two types of operations:

  1. Level-based judgment is used to reduce unnecessary parameter calculations for log operations to improve performance. function names and parameters are as follows:
                log.isFatalEnabled(); log.isErrorEnabled(); log.isWarnEnabled(); log.isInfoEnabled(); log.isDebugEnabled(); log.isTraceEnabled();                                    

    The following code can explain this well:

    If (log. isdebugenabled () {... some high-cost operations... log. debug (theresult );}

    If the Log facility level definition is higher than debug, these high-cost operations can be avoided.

  2. The other is log registration. log information is registered by level. The function name and parameters are as follows:
                log.fatal(Object message); log.fatal(Object message, Throwable t); log.error(Object message); log.error(Object message, Throwable t); log.warn(Object message); log.warn(Object message, Throwable t); log.info(Object message); log.info(Object message, Throwable t); log.debug(Object message); log.debug(Object message, Throwable t); log.trace(Object message); log.trace(Object message, Throwable t);                               

    There are two types of log registration operations: one parameter LOG registration operation and two parameter LOG registration operations. The former applies to all three types of users, and the latter is used to print the error stack information of the Log Registry, so it is more suitable for developers to adjust and maintain the use.

5.3 Configuration page

Commons-logging configurations can be set in system attributes, but this is a bad habit. system attributes affect all classes in the same JVM and are not easy to control, so the best place to configure commons-logging is in the commons-logging.properties file. When you use the attribute file to configure commons-logging, you must put it under the classpath of the software system.

The following two property items can be set in the commons-logging.properties:

  • Org. Apache. commons. Logging. Log

    The default logfactory Of Commons-logging is instantiated based on the value of this item to implement the Application Programming Interface log instance. If this item is not set, logfactory searches for classes that implement log interfaces in the following sequence in the classpath of the software system:

    1. Log4j
    2. Jsdks 1.4
    3. Jcl simplelog

    This rule is called a search policy.

  • Org. Apache. commons. Logging. logfactory overwrites the default logfactory implementation to meet specific requirements of the application system, such as redefinition of search policies.

5.4 example

5.4.1 source code

/** Created on 2003-6-5 ** to change the template for this generated file go to * WINDOW> preferences> JAVA> code generation> code and comments */import Org. apache. commons. logging. log; import Org. apache. commons. logging. logfactory; /*** @ author gongys ** to change the template for this generated type comment go to * WINDOW> preferences> JAVA> code generation> code and comments */public class Foo {priva Te static log = logfactory. getlog (FOO. class); Private string _ name; private int _ length; public static void main (string [] ARGs) {Foo = new Foo ("foo", 2 ); // check the log information generated by the normal length (log operation 1) Foo. set_length (12); // check the log information generated by unqualified names (log operation 2) Foo. set_name ("Jacky Bush"); // check the log information generated by the Invalid Length (log operation 3) Foo. set_length (-1); // check the log information generated by a qualified name (log operation 4) Foo. set_name ("Jacky Bush junior"); // check the specific log system (log operation 5) Log.info ("the log is instance of" + Log. getclass (). getname ();} public Foo (string name, int length) {This. _ name = Name; this. _ length = length;}/*** @ return */Public int get_length () {return _ length;}/*** @ return */Public String get_name () {return _ name;}/** mainly displays the usage of two types of log registration operations * @ Param length */Public void set_length (INT length) {stringbuffer loginfo = new stringbuffer (); if (length <= 0) {Loginfo. append ("length must be more than zero! This changing is ingored! "); Log. error (loginfo. tostring (), new throwable ("Invalid Length setting (" + Length + ")");} else {loginfo. append ("length is changed into"); loginfo. append (length); log. debug (loginfo. tostring (); _ length = length;}/** mainly used to display the level judgment using * @ Param name */Public void set_name (string name) {stringbuffer loginfo = new stringbuffer (); If (name. length () <get_length () & log. iswarnenabled () {loginfo. append ("Name's length must be more than"); loginfo. append (get_length (); loginfo. append (". So my name is not changed! "); Log. warn (loginfo. tostring (), new throwable ("invalid name setting (" + name + ")"); return;} If (log. isinfoenabled () {loginfo. append ("Oww! My name is changed into "); loginfo. append (name); loginfo. append ("! "); Log.info (loginfo. tostring () ;}_ name = Name ;}}

5.4.2 ant script and compilation

The ant script build. xml file contains the following content:

         <project name="loggingwork" default="compile" basedir="." > <target name="init">  <property name="lib.dir" location="libs" ></property>  <property name="src.dir" location="src" ></property>  <property name="bin.dir" location="bin" ></property>  <path id="classpath">       <fileset dir="${lib.dir}">             <include name="*.jar" />       </fileset>   </path> </target> <target name="compile" depends="init" >  <javac srcdir="${src.dir}" destdir="${bin.dir}" >        <classpath refid="classpath"/>     </javac> </target> <!-- <target name="run" depends="compile" >  <java classname="Foo" >        <classpath>         <pathelement location="bin"/>            <path  refid="classpath"/>        </classpath>      </java> </target> --></project>                        

Execute the command to compile the source code: ant compile

5.4.3 run scripts and run

The script is executed in a Windows environment and consists of two files.

Setlocalpath. BAT file:

@ Echo offset localpath = % localpath %; % 1run. BAT file: Set localpath = for % L in (libs /*. jar) Do call setlocalpath % ljava-CP "bin; % localpath %" foo

There is a commons-logging.jar file under libs.

Run the command./run. BAT to run the code.

5.4.4 running results and analysis

The following is the code running result:

1 2003-6-5 20:20:27 Foo set_name 2 warning: Name's length must be more than 12. So my name is not changed! 3 Java. lang. throwable: Invalid name setting (Jacky Bush) 4 at Foo. set_name (FOO. java: 76) 5 at Foo. main (FOO. java: 23) 6 2003-6-5 20:20:27 Foo set_length 7 critical: length must be more than zero! This changing is ingored! 8 Java. lang. throwable: Invalid Length setting (-1) 9 at Foo. set_length (FOO. java: 55) 10 at Foo. main (FOO. java: 24) 11 2003-6-5 20:20:27 Foo set_name 12 info: Oww! My name is changed into Jacky Bush junior! 13 2003-6-5 20:20:27 Foo main 14 Information: The log is instance of org. Apache. commons. Logging. impl. jdk14logger

For ease of analysis, I added a row number before each row. Log operation 1 uses the debug level, but the default Log Level of the encapsulated log system is higher than that of debug, so no output information is provided. 1-5 output information of Action Log operation 2, output information of Action Log operation 3, output information of Action Log operation 4, and output information of Action Log operation 5, indicates that the specific log system to be encapsulated is jdk14, which is determined by the search policy mentioned above.

Back to Top

6. Internal Parsing

The topic of commons-logging is the Log facility. To achieve the "facility" requirement, in addition to a good user interface, there must also be an excellent internal design. There are 6 main classes in the commons-logging.jar, the class relationship is shown in the diagram of commons-logging design, the gray part of the diagram shows the external class.

Log interface represents the application programming interface; logfactory represents the configuration interface, which reads configuration items and implements search policies.

6.1 Adaptation Mode

Commons-logging is a common implementation of log facilities. Although it provides the default Implementation of application programming interfaces (simplelog), it is mainly intended to encapsulate a powerful log system. With this understanding, we are faced with the following scenarios: one side has a ready-made log system, such as log4j and jdk14; the other side has an easy-to-use interface. We need a design that can coordinate the two sides. The design mode-adaptation mode is our ideal choice. To enhance the readability of this article, I reference the Adaptation Mode description in the following table:

Name Adapter
Structure
Intention Converts an interface of a class to another interface that the customer wants. The A d a p t e r mode makes those classes that cannot work together due to interface incompatibility work together.

The following table lists the elements in the Entity Adaptation Mode in the Commons-logging design diagram:

Serial number Entity in class diagram Elements in the Mode
1 Log Target
2 Jdk14logger Adapter
3 Log4jlogger Adapter
4 Logger (Java. util. Logging) Adaptee
5 Logger (Org. Apache. log4j) Adaptee

In the commons-logging design diagram, the adaptation mode is used twice: the first time is a general implementation composed of (1/2/4) in the table above and a jdk14 log adaptation, the second is a general implementation composed of (1/3/5) in the preceding table and the adaptation of log4j logs.

6.2 bind an Interface

Since commons-logging is a common interface, its implementation cannot be bound to a specific log system. We need a design that can implement this binding outside the code. Generally, we use a mode in the Gang of Four creational mode class to create an instance of the class implementing a certain interface. commons-logging uses the factory method mode to select a specific log implementation. The following table describes the factory method mode.

Name Factory method
Structure
Intention Defines an interface used to create objects, so that the subclass determines which class to instantiate. Factory method delays the instantiation of a class to its subclass.

The following is a comparison between each entity in the Commons-logging design diagram and each element in the factory method mode in the above table:

Serial number Entity in class diagram Elements in the Mode
1 Log Product
2 Jdk14logger Concreteproduct
3 Log4jlogger Concreteproduct
4 Simplelog Concreteproduct
5 Logfactory Creator
6 Logfactoryimpl Concretecreator

Logfactory is an abstract class. In addition to providing the log Creation Interface, logfactory is also responsible for searching extended logfactory classes, such as logfactoryimpl, which is responsible for creating log instances.

Logfactoryimpl extended logfactory. Except for creating logs, logfactoryimpl is mainly used to search for classes that implement log operation interfaces, such as log4jlogger.

Therefore, we have two search policies: the specific class search policy of logfactory and the specific class search policy of log. These two search policies provide the flexibility and scalability of the entire system.

The following code is the logfactory class method:

         public static Log getLog(Class clazz)         throws LogConfigurationException {         return (getFactory().getInstance(clazz));    }                        

To return a specific log class, the getlog method first calls the getfactory method to obtain the instance of the specific logfactory class, and then calls the getinstance method of the instance. The getfactory method implements the specific class search policy of logfactory; The getinstance method implements the specific class search policy of log.

6.2.1 Specific Class search policies of logfactory

Logfactory searches for the Class Name of the specific logfactory class in the following order:

  1. Use System attributes. If the system attribute org. Apache. commons. Logging. logfactory of the virtual machine is set when the software system is running, the value of this attribute is returned as the class name of the specific class that implements logfactory.
  2. Jdk1.3 jar service provider discovery mechanism. If classloader can find META-INF/services/org In classpath. apache. commons. logging. in the logfactory file, the value read from the first line of the file is the class name of the specific class implementing logfactory.
  3. Property configuration file. If classloader can find the commons-logging.properties file in classpath, The Org. Apache. commons. Logging. logfactory attribute value in this attribute file is the class name of the specific class implementing logfactory.
  4. Logfactoryimpl. If none of the above methods can find the Class Name of the specific class implementing logfactory, return the class provided by commons-logging itself: org. Apache. commons. Logging. impl. logfactoryimpl.

6.2.2 specific log search policies

Logfactoryimpl searches for the Class Name of the specific log class in the following order:

  • Property configuration file. If classloader can find the commons-logging.properties file in classpath, The Org. Apache. commons. Logging. Log attribute value in this attribute file is the class name of the specific class implementing log.
  • Use System attributes. If the system attribute org. Apache. commons. Logging. log of the virtual machine is set when the software system is running, the value of this attribute is returned as the class name of the specific class implementing log.
  • Check log4j. If you can find Org. apache. log4j. logger and org. apache. commons. logging. impl. log4jlogger, return Org. apache. commons. logging. impl. log4jlogger is used as the class name of the specific log class.
  • Check jdk14. If you can find Java. util. logging. logger and org. apache. commons. logging. impl. jdk14logger, return Org. apache. commons. logging. impl. jdk14logger is used as the class name of the specific log class.
  • The last card, simplelog. If none of the above methods can find the Class Name of the specific class implementing log, return the class provided by commons-logging itself: org. Apache. commons. Logging. impl. simplelog ";

Back to Top

7. Remaining Issues

Commons-logging is a common interface with a very simple user interface. This is an advantage, but it lacks support for the definition of the log target device, log format, and complete levels of support. Software systems that require these daily-to-facility features must seek other log facilities, such as log4j and jdk14log.

Commons-logging provides flexibility based on the configuration interface other than the code, but lacks (at least not perfect) the dynamic configuration interface when the program is running.

Back to Top

8. Summary

Commons-logging is a lightweight and easy-to-use logging facility that can be used with complex logging facilities, such as log4j and jdk14log. Commons-logging is not only a cover, but also a simple interface, but also a simple implementation-simplelog. Simplelog simply outputs all compliant log information to system. err. on the log target, it is the base card of the commons-logging search policy, so that the commons-logging Log facility can work normally even in the running environment of the software system where log4j and jdk14log cannot be found. If you want the complete function of the log facility, only using commons-logging cannot meet the requirements. In this case, the software system can use commons-logging and other log facilities at the same time, but we have to deal with two sets of user interfaces. Therefore, for software systems with powerful log Requirements, in the current status of commons-logging, it is best to use log4j or jdk14log separately.

In the internal design of commons-logging, it is worth mentioning that the interface Binding design is implemented. It creates an interface instance using the factory method mode, at the same time, two policies are used to find specific factory classes and log operation interface implementation classes respectively. The implementation of the two policies uses the class inheritance method. Readers can use the refactoring technology to implement it as the Gang of Four strategy mode.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.