Jungleford, if you have just contacted Java, just in Java, it is very uncomfortable, it is indeed good, including most of the IDE of M $, including VJ has been called "garbage" as a Java programmer. The class library (remember that people who have previously been on the Java of the Haicheng Cloud about VJ issues are likely to be sealed, ^ _ ^), its development tool is quite easy to debug. Java also has a debugging of command line and debugging of IDE, but now is like JB like JB is a huge thing, low-configuration machines may be a luxury, not like VC. What to do, the masters said, "My JDB is skilled", then I will report the eyes of the scenery, like the rookie like me, basically didn't make JDB, or old man in code system.out. Println (...). Until 1996, a project called "European Safety Electronics Market" (EU Semper) started, "Debug" is no longer a "physical activity", but a software design, the log management interface developed by this project group later Become a member of the Apache Jakarta project, it is the log4j we are familiar with. The following text will introduce some technologies associated with Java log, and the purpose is not to let you give up SYSTEM.PRINTLN (...) of the old earth, but said that there are many options in Java, you I feel that I have a senior weapon today, and tomorrow may be "outdated", huh, huh. The ancestor: system.out.println (...) Why still have to mention it again? After all, our habits are not so easy to change, and system.out (Don't forget to have system.err) is a PrintStream object that deals directly and consumers. It is the basis of the terminal display. Advanced Logger wants to display log content in the terminal. This will inevitably use this. A small-scale program debugging, properly using system.out.println (...) I think it is still a most convenient and most effective way, so we still put it at the beginning, so that you can't "Dissively Forgot the ancestors": ) Unsual use Keywords: Assert Assert may be more unfamiliar to most people, it is also a debugging tool, it seems to be the Dongdong, which is J2SE 1.4, a common usage is:
Assert (Boolean expression); there is no reflection when the expression is TRUE, and an assertionerror will be thrown if the False system will be thrown. If you want to use Assert, you must add "-Source 1.4" when compiling, add the "-ea" option at runtime. After birth: Java logging api, a glimpse of SYSTEM.OUT.Println (...) is far less than a high-demanding user, it is not a log system, a relatively complete log system should have an output medium, priority, format The functions such as log filtering, log management, parameter configuration. The Java log bag published with J2SE 1.4 Java.util.logging is a timely, in the program, in the program, and the rich debugging information is already a fairly Easy. 1. Logger: Logger Logger is a log function call interface that directly faces users. From the user's perspective, it completes most of the logging work, usually you get a logger object, just use some simple ways, such as Info Warning, Log, Logp, LogRB, etc., can complete the task, simply arrive with system.out.println (...) only one statement, but the background may be in the console, file, to the database, and even network At the same time, this information is output, and this process is completely transparent to the user. Before using Logger, you must first get a logger object by getLogger () or getanonymouslogger () static method (think about it. Is it a fact that is "factory method" in design mode? You can refer to Logger Source code, you will understand that logmanager is "factory class" and logger is "product class". Everything must be used to use, huh). Here we need to understand the concept of Logger's "Namespace": usually we need to clearly know where a variable is in any location, which method is exactly what is the use of this. When we use getLogger () to get the logger, you need to specify this Logger's namespace, usually a package name, such as "com.jungleford.test", etc. If you specify NameSpace, then you will register this Namespace in a global object logmanager. Logger will form a hierarchical relationship based on NameSpace, such as Namespace, "com.jungleford" Logger is the father of Namespace is the Logger of "com.jungleford.test", and the latter calls the getParent () method will return the former, if there is no NameSpace " The Logger "of com.jungleford" looks for the logger "COM", if you can't find the root Logger, "", "", the parent of the root Logger is NULL. In theory, this Namespace can be arbitrary, usually we are scheduled to press the object to be debugged, but if you are the logger generated using the GetAnonymousLogger () method, then there is no Namespace, this "anonymous logger" father is Root Logger. After getting a Logger object, you can log log, here is some common methods:
Finest, Finer, Fine, Info, Config, Warning, Severe: Simple method, the output log is the specified level. About the log level will be talked in detail later. Log: Not only can you specify a message and level, but also a number of parameters, or even a logRecord object (these parameters are an important part of the LogRecord object). LogP: More refined, not only has the functionality of the log method, but also you can define new class names and method names without current NAMESPACE. ENTERING, EXITING: These two methods are specifically managed when debugging, and the situation used to observe a variable change, just as we at the debug state of the VC, then press F10, huh, huh. 2. Output Media Control: The meaning of the Handler log is that it can be output in a variety of forms, especially the medium like a file that can be saved for a long time, which is unable to do. The Logging API's Handler class provides an interface for processing logging (LogRecord, which is an interface to a log message), including several implementation API: consolehandler: output to the console. FileHandler: Output to the file. SocketHandler: Output to the network. These three output controllers are subclasses of StreamHandler, and the Handler has a subclass of MemoryHandler. It has a special place, we will see later. The default handler is consolehandler when the program starts, but this is configurable, talk about the problem of the logging configuration file. In addition, users can customize their own output controllers, inheriting Handler, usually only need to implement three undefined abstract methods in Handler:
Publish: The main method, write the log record to the media you need. Flush: Clear the buffer and save the data. Close: Close the controller. We can easily implement a controller that write logs into the database by overwriting the above three methods. 3. Custom output format: Formatter In addition to the output medium, we may also want to have a variety of output formats, such as ordinary text, HTML form, XML, etc. to meet different views. Formatter in the Logging API is a class that provides a logging formatting method interface. By default, two formatter: SIMPLEFORMATTER: Standard log formats are usually in the form where they can often be seen under the console when starting some servers such as Tomcat, JBoss, just like this:
2004-12-20 23:08:52 Org.apache.coyote.http11.http11protocol init information: Initializing Coyote http / 1.1 on http-80802004-12-20 23:08:56 Org.apache.coyote.http11.http11protocol init Information: Initializing Coyote http / 1.1 on http-8443 xmlformatter: XML form of log format, your logger If add a new XMLFormatter (), you will see the following form under the console, but more commonly used is Use the FileHandler described above to the XML file:
XML Version = "1.0" encoding = "gbk" standalone = "no"?>
Type of integer OFF maximum integer (Integer.max_Value) Severe1000Warning900info800config700fine500finer400finest300ALL minimum integer (INTEGER.MIN_VALUE) You can also define your own log level, but pay attention to, not directly creating Level objects (because its constructor is protected by protected But by inheriting the way Level, such as:
Class Alertlevel Extends Java.util.logging.LOVEL {Public Alertlevel () {Super ("Alert", 950);}} ... Logger Logger = Logger.GetanonymousLogger (); Logger.log (New Alertlevel (), "a Dangerous Action! "); The above define a log level above Warning but below Severe. So there may be friends who will use the following statements to record an event:
Logger logger = logger.GetanonymousLogger (); logger.fine ("Everything Seems OK."); // or //logger.log (leTHING, "Everything Seems OK."); But a program runs, strange Why didn't you print any news? Let's talk about this problem in the next section. 5. Log Filter: Filter so-called filter is a component that controls which logs that do not output. The log you wrote above is not displayed on the console because the Logging API pre-set default level is info, which means that only the level is not lower than the log of INFO (ie, its integer value is not less than 800). Will be output, this is the function of Filter. So we can see Severe, Warning, INFO, and the Alert message we defined above, but you can't see Fine, Finer, and Finest messages. Of course, you use the Logger's SETLEVEL method or method to modify the configuration file (what is the configuration file, we will see it later) to redefine the lowest level of the Logger output. Filter can only filter the log level, you can also define your own Filter, implement it in the ISLogGable method, follow any information carried by LogRecord, such as (by the way, review anonymous class, huh): logger logger = logger.getanonymousingLogger (); logger.setfilter (new filter () {public boolean isloggable (logRecord REC) {// Get filter information}} from logRecord}}); 6. Predefined parameters LogManager is a global object that implements Singleton mode (because it is A unique object, LogManager needs to be thread secure), which manages all registered (package hierarchical) or anonymous Logger, and related configuration information. The configuration information here is usually obtained from the
######################################################################################################################################################################################################################################################################################################## ########### DEFAULT Logging Configuration File ## You can Use a different file by specifying a filename # with the java.util.logging.config.file system property. # For example java -djava.util .logging.config.file = myfile ############################################################################################################################################################################################################# ######################################################################################################################################################################################################################################################################################################## ########################################################################################################################################################################################################################################################################################################## ################################### "Handlers" Specifies a comma Separated List of log Handler # classes. These handlers will be installed during VM startup. # Note that these classes must be on the system classpath. # By default we only configure a ConsoleHandler, which will only # show messages at the INFO and above levels.handlers = java.util.logging.ConsoleHandler # To also add the FileHandler, use the following line instead. # handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler # Default global logging level. # This specifies which kinds of EVE nts are logged across # all loggers. For any given facility this global level # can be overriden by a facility specific level # Note that the ConsoleHandler also has a separate level # setting to limit messages printed to the console..level = INFO ## ######################################################################################################################################################################################################################################################################################################## ######### Handler specificial proties. # Describes specific configuration info for handlers. ###################################################################################################################################################################################################################################################################### ######################## ome directory.java.util.logging.filehandler.pattern =% h / java% u.logjava.util.logging.fileHandler.limit = 50000java.util.logging.fileHandler.count = 1java.util.logging.fileHandler.Formatter =
java.util.logging.XMLFormatter # Limit the message that are printed on the console to INFO and above.java.util.logging.ConsoleHandler.level = INFOjava.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter # ######################################################################################################################################################################################################################################################################################################## ########## Facility Specific Properties. # Provides extra control for each logger. #################################################################################################################################################################################################################################################### ######################################################################################################################################################################################### : com.xyz.foo.Level = Severe You can change the behavior of the runtime logger by modifying this profile, such as: .level defines the minimum log level of the default output mentioned above; XXXHandler related attributes define a variety of Output medium, etc.. It is more interesting about the log file, which is FileHandler, of course, you can create a FileHandler in the program, then add to Logger: FileHandler Fhd = New FileHandler ("% h / java% u.log", 5000, 1 , true); fHD.SETLEVEL (Level.all); FHD.SETFORMATTER (New XMLFormatter ()); Logger.AddHandler (FHD); this code is equivalent to the text paragraph in Logging.properties:
java.util.logging.FileHandler.pattern =% h / java% u.logjava.util.logging.FileHandler.limit = 50000java.util.logging.FileHandler.count = 1java.util.logging.FileHandler.formatter = java.util .logging.xmlformatter here's Pattern represents a log file name defined with an escape character:
Symnial string enlighten the sense% T temporary directory% H user directory, that is, the value of the system attribute "user.home" corresponding to the value g of a randomly generated number, can repeat% u A randomly generated non-repeated number above "% h /java%u.log "Taking the log file in Windows 2000, the log file may be: c: / documents and settings / administrator / javax.log. Here x represents a non-repetitive number, if it is the first time, then java0.log; if there is a java0.log file in this directory, then Logger generates a new log file for java1.log. Of course, you can use your own profile in other places, but you need to specify the java.logging.config.file property when starting the program:
Java -djava.logging.config.File = ... 7. There is also a method of resource and localized logger called LOGRB, which may not be used by beginners. If the JDK you install is an international version, you will see info output in the Chinese Windows platform log output, Warning displayed "information", "warning" and other Chinese characters. Because LOGRB is a method related to Java I18N / L10n, you can define your own "resource bundle" and then specify the corresponding resource name in the LogRB method, then you can see yourself in the output log. Information defined locally, time, etc. If you are interested in i18n / l10n, you can refer to the Java Localization documentation. After understanding the above components, we review the work process of a complete log processing: Program launch log service, create a logger object, logmanager organizes logger in accordance with the Namespace hierarchy, inherits the parent's property; at the same time, Logmanager Read the appropriate properties from logging.properties to initialize Logger, if the properties are set in the program, use new configurations. When the application generates a log, the Logger will create a LogRecord object that encapsulates all the information of a log. Logger needs to determine if the log needs to be output according to the current setting, and transmits the useful log to the corresponding Handler process, and the handler converts the log message into a certain display format according to the current settings of Formatter and Resource Bundle, then output Go to a predetermined medium (console, file, etc.). The whole process is roughly as shown in Figure 1: Figure 1 We mentioned a special class called MemoryHandler when introducing Handler, here we have to understand the concept of "Handler Chain", the log may pass multiple Handler before output Processing, MemoryHandler In this case, it is an intermediate role that maintains a log buffer in memory. When the log does not fill the buffer, send all the logs to the next handler, otherwise the new log will overwrite the most Older logs, so using MemoryHandler can maintain a certain capacity log, and MemoryHandler can also format it without using formatter to format it, thereby high efficiency. An example using the handler chain is shown in Figure 2: Figure 2
From the blue: Apache Jakarta log4j log kit to deal with daily log demand, J2se's logging API can say that it has been made quite well, but the pursuit of perfect developers may need to be more scalable, better professional log processing tools, log4j is currently currently currently current A popular toolkit, it provides more output media, output formats, and configuration options, you will find that some features that still need to be built in J2se still need to be implemented in log4j. About log4j I may talk too much, you can look at "Reference Information" after the article, there is also a detailed introduction online, I am doing a contrast, because the log4j and j2se 1.4 logging API usage is Very similar, some different components you will find that the status they live is actually the same:
J2SE 1.4 classes in the class log4j logger LoggerLogger Log Manager LogManagerLogManager log object LogRecordLoggingEvent output media format FormatterLayout level control HandlerAppender LevelLevel filter FilterFilter log4j can do better finer control, there are no such ready-made to the database J2SE The method of writing the log, but log4j has JDBCAPPENDER, which can even go to the GUI graphical interface (LF5Appender, a hierarchy displayed in JTREE mode), Windows NT Event Viewer, UNIX Syslogd Server (SyslogaPpender) , Electronic mailbox (SMTPAPPENDER), JMS message (JMSAppender) output log, cow bar; J2se can only use% java_home% / jre / lib / logging.properties to do configuration files, but log4j can be Set the Properties file or XML format in the code in the code. The other aspects of log4j is equally rich. In short, log4j's biggest feature is "flexible", whether it is appender, Layout or Configurator, you can easily make the log into almost anything you want. Framework and Standard: JSR motion Saix time, log4j is more than J2se logging API, many concepts are LOG4J, but becoming a standard, it is formed in JSR 47. Some people may not know about JSR, which is also to talk about JCP, "Java Community Process", which is an open organization established in 1998 to develop private standards for Java technology, you can pass http: // www .jcp.org / en / participation / membership application becomes its payment or free member, JCP's main job is to formulate and release JSR (Java Specification Requests), JSR's meaning of Java is equivalent to RFC for network technology, due to Jugglers of JCP members make JSR a important criterion for JAVA. JSR 47, "Logging API Specification", develops debugging and log frameworks, and the J2SE Logging API is an implementation of the framework.
For various reasons, the log4j has become a mature technology before JSR 47, so that log4j has a certain advantage, but it is not possible to say that JSR 47 is an outdated norm, the standard is always developing. ! Not all: Other log processing tools In addition to J2se Logging API and Log4j, there are other technologies: Jakarta's COMMONS logging is a nice choice, it is a bit similar to GSS-API (General Security Services Interface), its log service mechanism can be replaced, that is, can use the J2SE Logging API to use log4j, but JCL provides consistent interfaces to developers, this is quite important, component can Reuse is a goal pursuing Jakarta Commons project; IBM Jlog is also a toolkit that is launched by J2se Logging API, but Jlog is a commercial product. As for the application of the log API, there are more, which big one big tool or platform does not use the log module? Tomcat, JBoss ... I said so much, one thing we don't need to know is that "debug" is also a knowledge. When we use system.out.println (...) and very cool, we should also think about it, how to make such a rookie statement can become humanized and colorful. Reference Java Logging Documentation Java Logging Apis J2se Advanced, by www.javaresearch.org Short Introduction To Log4j, by CEKI Gülcü log4j Apis FAQ About log4j