. Exceptions, assertions, logs in Java "under the draft, log4j topic" __java

Source: Internet
Author: User
Tags deprecated exception handling log4j
(This chapter mainly explains the core of the Java content-exception handling, Java exception handling mechanism, consistent is a relatively complex piece, and many times if the program can properly pay attention to the corresponding exception handling situation, then the development process to save a large part of the time, The most common situation is to assist with debugging and maintenance work, as well as improve the system's fault tolerance and stability. This chapter is not the same as the previous class and object chapters, and this chapter may cover less than the previous chapter, but I will try to make sure that in the entire article the details of the exception and the corresponding development experience that need to be noticed in the development process are written into this article, and the starting point of this chapter is exception handling, and the core content includes testing, debugging, and deployment and other related content as well. If there is a clerical error, please come to the email guide: silentbalanceyh@126.comThank The contents of this chapter 1.Java Exception Handling 2. Exception handling Experience 3. Use of assertions 4. logs in Java (JDK1.4 Logging Framework) 5. Third-party Log library (log4j, Commons Logging Framework) 5. Third-party log library (log4j,commons Logging Framework)

The official log framework JDK 1.4 Logging Framework is presented, followed by a description of the two Third-party log framework log4j and the Commons Logging framework, which is also the most used log framework for the entire Java community. Download Address: "Direct copy can be downloaded"Http://apache.freelamp.com/logging/log4j/1.2.15/apache-log4j-1.2.15.zip    Http://labs.xiaonei.com/apache-mirror/logging/log4j/1.2.15/apache-log4j-1.2.15.zip
   Http://apache.etoak.com/logging/log4j/1.2.15/apache-log4j-1.2.15.zip    i.log4j:    1) Basic introduction:Log4j is an open source project for Apache, by using log4j, we can control the destination of log information delivery is console, file, GUI component, even interface server, NT Event recorder, UNIX syslog daemon, etc. We can also control the output format of each log, and by defining the level of each log information, we can control the log generation process more carefully. Most interesting of all, these can be configured flexibly with a single configuration file without the need to modify the applied code. In addition, by log4j other language interfaces, you can use log4j in C, C + +,. Net, and Pl/sql programs, and its syntax and usage, as in Java programs, make a unified and consistent Log component module for a multilingual distributed system.   Also, by using a variety of third-party extensions, you can easily integrate log4j into Java EE, Jini, and even SNMP applications. Overall, there are three of the most important core components in log4j:LoggerAppenderAndLayout, not only that, it also allows developers to customize multiple logger, each logger has its own name, logger between the name to represent the affiliation relationship. But there is a logger called root, this logger cannot be retrieved by name, but can be obtained directly using Logger.getrootlogger (), and other logger can use Logger.getlogger (String name ) method getsLogger:Receives log requests generated by the log statement when the application is executed. It is an important log processing component that can be accessed through the logger class of the log4j API. Its methods are: Debug, info, warn, error, fatal, and log. These methods are used to record messages.Appender:Manages the output of the log statement. When a log statement is executed, the Logger object receives the record request from the log statement. This request is sent via logger to Appender. Appender then writes the output to the user's chosen destination. For different log destinations, different appender types are provided. These appender include: File appender for files, JDBC appender for databases, and SMTP Appender for SMTP servers.
   Layout:Used to specify the format used by Appender to write a log statement to the log destination. The various layouts that Appender can use to format output include simple layouts, pattern layouts, and HTML layouts.[1] First look at the LOG4J package directory structure:Org.apache.log4j:log4j The main classes, interfaces, and specialAppender class, Layout, level and loggerORG.APACHE.LOG4J.SPI: Includes an extension of the Spi--system programming Interface Org.apache.log4j.chainsaw for the SPI: Java based A GUI log viewer for Swing:
Org.apache.log4j.config: Used to set or get the related properties of certain components Org.apache.log4j.helpers: A collection of multiple classes that are used only by the log4j library, usually not externally ORG.APACHE.LOG4J.JDBC: A related event Appender used to record JDBC connections ORG.APACHE.LOG4J.JMX: JMX-based logging that can be configured when JMX is developed, but the classes in the package are not particularly stable Org.apache.log4j.lf5: "There is little use, I do not know this part of the use, did not use the" org.apache.log4j.net: Used for remote logging of the Appender, mainly for JMS, SMTP and socket based logging, which is used to send logs to a log4j server for remote logging Org.apache.log4j.nt:Java application of local interface"JNI", interface in Java, implementation with C code, used to record the Windows NT system event Log Appender Component org.apache.log4j.or: Help class Render operations on object type Org.apache.log4j.performance: Performance Test Code Org.apache.log4j.xml: Contains multiple XML components, using DOM tree structure in log4j environment to record XML-formatted logs Org.apache.log4j.varia: Includes multiple appender and filters and other related components[2]log4j Installation:log4j download After the need for a simple installation, first to ensure that the original system environment and the Java environment is normal: Download log4j jar package, the top has provided a download address to extract these packets into a directory,"*: It is generally better for developers to put the jar's package classification under different directories for easy use. "To the bottom of the packageLog4j-1.2.15.jarInto the development of the classpath inside, about Java inside classpath Some of the problems left to the development of Java inside to explain also need to download two auxiliary parse XML jar, download the addresshttp://archive.apache.org/dist/xml/xerces-j/, here i download the latest version of 2.9.0, take out the inside of theXercesimpl.jarAndXml-apis.jarTwo jar files are placed inside the classpath."*: There is a special setting for CLASSPATH in the IDE environment, and the best way to prevent jar collisions is to keep the Java-standard environment in classpath."    2) The core concept of log4j: [Logger in 1]log4j:Logger is a core concept in log4j, which is the core component within the log process, in log4j, logger is divided into six logging levels, defined in the Org.apache.log4j.Level class:TRACE: This granular information time is not only for debugging,DEBUG: Indicates that fine-grained informational events are very helpful for debugging applications, which are primarily used to assist developers in debugging;INFO: This level indicates that the application's running process is highlighted on a fine-grained scale on the messageWARN: Indicates a scenario where potential errors may occurERROR: Indicates that although an error event occurred in the program, it still does not affect the continued operation of the systemFATAL: This level indicates that each critical error time will cause the application to exit. There are two very special levels, depending on the description in the API: All: This is the lowest level to open all log records off: This is the highest level and is used to turn off all logging. In general, the recommended development process uses onlyERROR, WARN, INFO, DEBUGFour levels, the following figure illustrates how these levels relate to one another:
As you can see from the illustration above, the log message is output only if the log level of the logger logger is higher than or equal to the level of the output message.   By default, the Logger level is debug, and if we need to create a Logger, there are several ways: Create a root logger: Logger Logger = Logger.getrootlogger ();   Create a new logger: Logger Logger = new Logger ("MyLogger");   Create a class-based logger: Logger Logger = new Logger (myclass.class);   Set the level of a log in log4j using the statement: Logger.setlevel (Level.debug); "*: Before the 1.2 version, log4j did not use the logger class, mainly using the category class, starting from version 1.2 to use the Logger class, the way above to create logger" here first read a piece of code, and then a detailed description of the category, actually fromVersion 1.2Start category and logger is a parent-child relationship, logger inherits from the category class, where we typically use category to create a logger, in the previous version category is equivalent to the logger we see now. InVersion 1.2, category is marked asdeprecated, and directly replaces it with logger, which in general Java is marked asdeprecatedMethods and classes have alternative methods and classes for the corresponding function of the version update, we generally in the development process as far as possible to avoid the use of markeddeprecatedClass or method. The following code is an upgraded change://Discarded code form: Category cat = category.getinstance ("Foo.bar");   The form currently used to create Logger: Logger Logger = logger.getinstance ("Foo.bar"); In order to make the contents of the above graphics easier to understand, here is another piece of code: package org.susan.java.logging;
Import Org.apache.log4j.Level; Import Org.apache.log4j.Logger;
Class foo{}
public class Log4jleveltester {public static void main (String args[]) {Logger Logger = Logger.getlogger (foo.class); Logge R.setlevel (Level.info);
The request is allowed becauseWARN >= INFOLogger.warn ("Low fuel level.");
The request was forbidden on the back becauseDEBUG < INFOLogger.debug ("Starting search for nearest gas station."); The code above is a good illustration of the use of logger when dealing with level, when Setlevel logger set the level of the logger itself, and then use the corresponding Warn, The Debug method determines the detailed comparison of the method used and the level of the logger setting, and the log information is output when the criteria for the above diagram are met. One thing to note here is the method warn and debug, both of which are not methods of the logger class, but rather a category method inherited from its parent class, where the method is compared and judged against the level of the log we originally set up. The final decision is whether to be recorded. Then we execute the program when the environment is well configured."Exceptions"Here will be a beginner log4j common problem, we will find that the console only this output: Log4j:warn No appenders could be found to logger (Org.susan.java.logging.Foo).   Log4j:warn Please initialize the log4j system properly. In the system environment, it is not found that we need the configuration file, the general understanding is the lack oflog4j.propertiesProperty file, where, if we don't use a configuration file, we'll modify the code below to: Package org.susan.java.logging;
Import Org.apache.log4j.BasicConfigurator; Import Org.apache.log4j.Level; Import Org.apache.log4j.Logger;
Class foo{}
public class Log4jleveltester {public static void main (String args[]) {basicconfigurator.configure (); Logger Logger = Logger.getlogger (Foo.class); Logger.setlevel (Level.info);
The request is allowed becauseWARN >= INFOLogger.warn ("Low fuel level.");
The request was forbidden on the back becauseDEBUG < INFOLogger.debug ("Starting search for nearest gas station."); } }

Related Article

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.