Directory 1. Introduction 2. Installation 3. log4j Basic Concepts 3.1. Logger 3.2. Appender 3.2.1. Use Consoleappender 3.2.2. Use Fileappender 3.2.3. Use Writerappender 3.3. Layout 3.4. Basic example 3.4.1 Simplelayout and Fileappender. 3.4.2 Htmllayout and Writerappender. 3.4.3 Patternlayout and Consoleappender. 4. Use external configuration files 5. Reference materials (and some links with reference value) 1. Introduction The logging in the program development environment is composed of statements embedded in the program to output some useful information to the developer. For example, trace statements (trace), structure dumps, and common System.out.println or printf debug statements. LOG4J provides a classification method for embedding a logging statement in a program. Log information has multiple output formats and multiple output levels. With a dedicated logging package, you can mitigate the maintenance costs of thousands of SYSTEM.OUT.PRINTLN statements, because logging can be controlled at run time through configuration scripts. LOG4J maintains the logging statements embedded in program code. By standardizing the process of logging, some people think that more log records should be encouraged and more efficient. 2. Installation In order to use the logging tool we are about to install, you must also set up an operating environment in which the tool knows where to find the information it needs, and the operating system knows where to find the tool. So, how to do it. In fact, it requires changing the operating environment. I have some qualifications for this document. Configuring a Windows Working environment and configuring a Unix Working environment. Download the log4j release from Http://jakarta.apache.org/log4j/docs/download.html. Extract the archive file into the appropriate directory. Add the file Dist/lib/log4j-1.2.6.jar to the CLASSPATH environment variable. The basic concept of 3.log4j The use of log4j involves about 3 main concepts: public class Logger Logger is responsible for most of the operations that log records are processed. public interface Appender Appender is responsible for controlling the output of logging operations. Public abstract class layout Layout is responsible for formatting the appender output. 3.1.Logger The log recorder (Logger) is the core component of log processing. LOG4J has 5 levels of normal (level). Available level levels (excluding custom level levels) for the logger (Logger), the following is an excerpt from the log4j API (http://jakarta.apache.org/log4j/docs/api/index.html): Static level DEBUG The debug level indicates that fine-grained informational events are useful for debugging applications. Static level INFO The INFO level indicates that the message highlights the application's running process at the coarse-grained levels. Static level WARN The WARN level indicates a scenario where a potential error occurs. Static level ERROR The error level indicates that, while an incorrect event occurs, it does not affect the continued operation of the system. Static level FATAL FATAL level indicates that each serious error event will cause the application to exit. In addition, there are two special logging levels available: (The following description comes from the log4j API http://jakarta.apache.org/log4j/docs/api/index.html): Static level All All levels are the lowest level and are used to open all log records. Static level off Off levels are the highest level and are used to turn off all log records. The behavior of the log recorder (Logger) is hierarchical. As shown in the following table: Figure-Log output level The logger (Logger) will only output information that is higher than or equal to its level. If the level of the Logger (Logger) is not set, it inherits the level of the nearest ancestor. Therefore, if you create a logger (Logger) in the package Com.foo.bar and there is no level set, it inherits the level of the Logger (Logger) created in the package Com.foo. If a logger (Logger) is not created in Com.foo, the log logger (Logger) created in Com.foo.bar inherits the level of the root logger (Logger). The root logger (Logger) is often instantiated and available, and its level is debug. There are many ways to create a logger (Logger), and the following method can retrieve the root logger: Logger Logger = Logger.getrootlogger (); You can also create a new logger like this: Logger Logger = Logger.getlogger ("MyLogger"); A more common use is to instantiate a static global logger based on the class name: static Logger Logger = Logger.getlogger (Test.class); All of these created "logger" loggers can set levels in the following ways: Logger.setlevel (level) level.warn); You can use any of the 7 levels; Level.debug, Level.info, Level.warn, Level.error, Level.fatal, Level.all and Level.off. 3.2.Appender Appender controls how the log is exported. Some of the available appender (the http://jakarta.apache.org/log4j/docs/api/index.html described in the Log4j API) are listed below: Consoleappender: Use user-specified layout (layout) to output log events to System.out or System.err. The default target is System.out. Dailyrollingfileappender extends Fileappender, so multiple log files can be logged as a single user-selected frequency. Fileappender writes log events to a file Rollingfileappender expands fileappender log files with a certain size of backup capacity. Writerappender writes log events to writer or outputstream according to the user's choice. Smtpappender when a particular log event occurs, an e-mail message is usually sent when an error or a significant error occurs. Socketappender sends a log event (Loggingevent) object to a remote log server (typically a network socket byte point). Sockethubappender sends a log event (Loggingevent) object to a remote log server group (typically a network socket byte point). Syslogappender sends a message to the background daemon (daemon) for remote asynchronous logging. Telnetappender a log4j appender that is designed to send messages to a read-only network socket. You can also implement the Appender interface to create a appender that logs output in its own way. 3.2.1. Use Consoleappender Consoleappender can be created in this way: Consoleappender Appender = new Consoleappender (new Patternlayout ()); A console Appender is created with a default patternlayout. It uses the default System.out output. 3.2.2. Use Fileappender Fileappender can be created in this way: Fileappender appender = null; try { Appender = new Fileappender (new Patternlayout (), "filename"); catch (Exception e) {} The constructor used above: Fileappender (Layout Layout, String filename) Instantiates a fileappender and opens the file specified by the variable "filename". Another useful constructor is: Fileappender (Layout Layout, String filename, boolean append) Instantiates a fileappender and opens the file specified by the variable "filename". This constructor can also choose whether to append the specified file to the output. If you do not specify a value, the default method is append. 3.2.3. Use Writerappender Writerappender can be created in this way: Writerappender appender = null; try { Appender = new Writerappender (new Patternlayout (), New FileOutputStream ("filename"); catch (Exception e) {} This writerappender uses constructors with patternlayout and OutputStream parameters, in which case fileoutputstream is used to output to a file. Of course, it also has other constructors that are available. 3.3.Layout Appender must use a Layout associated with it so that it knows how to format its output. Currently, LOG4J has three kinds of layout: Htmllayout formatted log output as HTML table. Patternlayout formats the log output according to the specified transformation mode, or uses the default conversion mode if no conversion mode is specified. Simplelayout formats the log output in a very simple way, printing level levels, followed by a dash "-", and finally a log message. 3.4. Basic example 3.4.1.SimpleLayout and Fileappender Here is a very simple example of a program that implements Simplelayout and Fileappender: Import Org.apache.log4j.Level; Import Org.apache.log4j.Logger; Import Org.apache.log4j.SimpleLayout; Import Org.apache.log4j.FileAppender; public class Simpandfile { static Logger Logger = Logger.getlogger (Simpandfile.class); public static void Main (String args[]) { Simplelayout layout = new Simplelayout (); Fileappender appender = null; try { Appender = new Fileappender (layout, "Output1.txt", false); catch (Exception e) {} Logger.addappender (Appender); Logger.setlevel (level) level.debug); Logger.debug ("Here is some debug"); Logger.info ("Here is some info"); Logger.warn ("Here is some warn"); Logger.error ("Here is some error"); Logger.fatal ("Here is some fatal"); } } You can download: Simpandfile.java. You can also view its output: Output1.txt. 3.4.2.HTMLLayout and Writerappender Here is a very simple example of a program that implements Htmllayout and Writerappender: Import java.io.*; Import Org.apache.log4j.Level; Import Org.apache.log4j.Logger; Import Org.apache.log4j.HTMLLayout; Import Org.apache.log4j.WriterAppender; public class Htmlandwrite { static Logger Logger = Logger.getlogger (Htmlandwrite.class); public static void Main (String args[]) { Htmllayout layout = new Htmllayout (); Writerappender appender = null; try { FileOutputStream output = new FileOutputStream ("output2.html"); Appender = new Writerappender (layout,output); catch (Exception e) {} Logger.addappender (Appender); Logger.setlevel (level) level.debug); Logger.debug ("Here is some debug"); Logger.info ("Here is some info"); Logger.warn ("Here is some warn"); Logger.error ("Here is some error"); Logger.fatal ("Here is some fatal"); } } You can download: Simpandfile.java. You can also view its output: Output1.txt. 3.4.3.PatternLayout and Consoleappender Here is a very simple example of a program that implements Patternlayout and Consoleappender: Import Org.apache.log4j.Level; Import Org.apache.log4j.Logger; Import Org.apache.log4j.PatternLayout; Import Org.apache.log4j.ConsoleAppender; public class Consandpatt { static Logger Logger = Logger.getlogger (Consandpatt.class); public static void Main (String args[]) { Note,%n is newline String pattern = "milliseconds since program start:%r%n"; Pattern + + "Classname of Caller:%c%n"; Pattern + = "Date in ISO8601 format:%d{iso8601}%n"; Pattern + + "Location of Log event:%l%n"; Pattern + = "message:%m%n%n"; Patternlayout layout = new Patternlayout (pattern); Consoleappender Appender = new Consoleappender (layout); Logger.addappender (Appender); Logger.setlevel (level) level.debug); Logger.debug ("Here is some debug"); Logger.info ("Here is some info"); Logger.warn ("Here is some warn"); Logger.error ("Here is some error"); Logger.fatal ("Here is some fatal"); } } You can download: Simpandfile.java. You can also view its output: Output2.txt. 4. Use external configuration files Often used in conjunction with external log files, so many options do not have to be hard-coded in the software. The advantage of using an external configuration file is that modifying the optional option does not require recompiling the program. The only drawback is that the speed is slightly slower due to the IO instruction. There are two methods that can be used to specify an external profile: a text file or an XML file. Now that everything is written as an XML file, the tutorial focuses on XML file methods, but it also contains examples of related text files. First, take a look at the following XML configuration file example: <?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE log4j:configuration SYSTEM "LOG4J.DTD" > <log4j:configuration xmlns:log4j= "http://jakarta.apache.org/log4j/" > <appender name= "Consoleappender" class= "Org.apache.log4j.ConsoleAppender" > <layout class= "Org.apache.log4j.SimpleLayout"/> </appender> <root> <priority value = "Debug"/> <appender-ref ref= "Consoleappender"/> </root> </log4j:configuration> The file starts with a standard XML declaration, followed by a DOCTYPE declaration that identifies the DTD (the document type definition), which defines the structure of the XML file, such as what elements can be embedded in other elements, and so on. The above file is in the Src/java/org/apache/log4j/xml directory of the log4j release. Then look at the log4j:configuration element that encapsulates all of the elements, which is specified as the root element in the DOCTYPE declaration. There are two structures embedded in the root element: <appender name= "Consoleappender" class= "Org.apache.log4j.ConsoleAppender" > <layout class= "Org.apache.log4j.SimpleLayout"/> </appender> Here, create a appender called "Consoleappender", note that you can choose any name, and the example chooses "Consoleappender" for the design of the sample. The Appender class is then given in full name, often with the canonical (fully qualified) class name. The appender must have a specified name and class. Embedded within the Appender is the layout element, where it is specified as Simplelayout. Layout must have a class attribute. <root> <priority value = "Debug"/> <appender-ref ref= "Consoleappender"/> </root> The root element must exist and cannot be quilt-class. The priority in the example is set to "Debug", and the setting Appender is full of a appender-ref element. There are more attributes or elements that can be specified. View the SRC/JAVA/ORG/APACHE/LOG4J/XML/LOG4J.DTD in the log4j release for more information about the XML configuration file structure. You can read the configuration information file into the Java program in the following way: Domconfigurator.configure ("Configurationfile.xml"); Domconfigurator uses a DOM tree to initialize the log4j environment. Here is the XML configuration file in the example: Plainlog4jconfig.xml. Here is the program that executes the configuration file: Files/externalxmltest.java: Import Org.apache.log4j.Logger; Import Org.apache.log4j.xml.DOMConfigurator; public class Externalxmltest { static Logger Logger = Logger.getlogger (Filetest.class); public static void Main (String args[]) { Domconfigurator.configure ("Xmllog4jconfig.xml"); Logger.debug ("Here is some debug"); Logger.info ("Here is some info"); Logger.warn ("Here is some warn"); Logger.error ("Here is some error"); Logger.fatal ("Here is some fatal"); } } Here is an XML configuration file that implements the logger logger with the Patternlayout Fileappender: <?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE log4j:configuration SYSTEM "LOG4J.DTD" > <log4j:configuration xmlns:log4j= "http://jakarta.apache.org/log4j/" > <appender name= "Appender" class= "Org.apache.log4j.FileAppender" > <param name= "File" value= "Indentify-log.txt"/> <param name= "Append" value= "false"/> <layout class= "Org.apache.log4j.PatternLayout" > <param name= "Conversionpattern" value= "%d [%t]%p-%m%n"/> </layout> </appender> <root> <priority value = "Debug"/> <appender-ref ref= "Appender"/> </root> </log4j:configuration> You can download the example from here: Xmllog4jconfig2.xml. For more examples of using an XML file to configure the log4j environment, check the directory src/java/org/apache/log4j/xml/examples/for the log4j release. This is the configuration file in the form of the text file discussed above: # initialise Root logger with level DEBUG and call it blah Log4j.rootlogger=debug, blah # Add a consoleappender to the logger blah Log4j.appender.blah=org.apache.log4j.consoleappender # Set set ' layout to be simplelayout Log4j.appender.blah.layout=org.apache.log4j.simplelayout From here you can download: Plainlog4jconfig.txt. This is the program that executes the configuration file: Import Org.apache.log4j.Logger; Import Org.apache.log4j.PropertyConfigurator; public class Externalplaintest { static Logger Logger = Logger.getlogger (Externalplaintest.class); public static void Main (String args[]) { Propertyconfigurator.configure ("Plainlog4jconfig.xml"); Logger.debug ("Here is some debug"); Logger.info ("Here is some info"); Logger.warn ("Here is some warn"); Logger.error ("Here is some error"); Logger.fatal ("Here is some fatal"); } } You can download an example using this profile: Externalplaintest.java. For more examples of using a text file to configure the log4j environment, check the directory examples in the log4j release. The example of using an external configuration file is simply discussed here, and it should now be certain that you have the ability to independently learn more examples from log4j Distributions and Beta editions. 5. Reference materials (and some links with reference value) Http://jakarta.apache.org/log4j/docs/manual.html Concise Introduction to Log4j-Ceki G-March 2002 Http://www.vipan.com/htdocs/log4jhelp.html Don't use SYSTEM.OUT.PRINTLN. With Log4j-vipan Singla http://www.opensymphony.com/guidelines/logging.jsp Getting Started with Log4j/opensymphony log records Http://builder.com.com/article.jhtml?id=u00820020124kev01.htm Add logging to your Java application-Kevin Brown |