To be honest, in addition to log4j's function, I prefer its logo. The following note is mainly "Borrow from" log4j's random document "Short Introduction to log4j", written by CEKI Gülcü in March 2002, other reference documents See it. 1, log4j has been ported to C, C , C #, Perl, Python, Ruby, Eiffel several languages. 2, log4j has three main components: recorder, storage device, layout 3, recorder (recorder can not care about log data storage) log4j allows programmers to define multiple recorders, each recorder has its own name By the name between the recorder, it indicates the affiliate relationship (or family relationship). Such as the recorder A.B, between the recording A.b.c is a parent child relationship, and the recorder A and A.b.c are the relationship between ancestors and future generations, and the father and child relationship is the special case of the ancestors and progeny. With this relationship, logical relationships between different recorders can be described. There is a recorder called the root recorder, which is always existed and cannot be retrieved or referenced by name, and it can be obtained through the logger.getrootlogger () method, and the general logger is passed through the Logger.getLogger method. Below is the basic method of the Logger class. package org.apache.log4j; public class Logger {// Creation & retrieval methods: public static Logger getRootLogger (); public static Logger getLogger (String name); // printing methods: public void debug (Object message); public void info (Object message); public void warn (Object message); public void error (Object message); public void fatal (Object message); // generic printing method: public void log (Level l, Object message);} recorder further There is an important attribute that is level. (This is a good understanding, just like a family, there is a generation of generations, but the height of different members may not be the same, and the height and generations have nothing to do) programmers can give different recorders to different levels, if A member is not explicit, and the nearest level value is automatically inherited. The root recorder has a total level value. For example, the level value inherited by the level value assigned by the recorder name Root ProT ProT x PX PX X.Y None PX X.y.z None PX programmer can freely define the level. There is a prejudice relationship between the level value, and there is a level value of each of the LOG information to be output, and there is a level value. In the previous logger class, several levels of Debug, Info, Warn, Error, Fatal are predefined. Because of the method binding, people are easy to misunderstand, in fact, these methods only indicate the log information to be recorded. level. When the log () method is called, the level of log information needs to be explicitly specified by parameters. If a log information is level, it is greater than the level value equal to the logger, then the logger will record it. If you feel difficult to understand, you can refer to the following example.
// Get a logger instance named "com.foo" logger logger = logger.getlogger ("com.foo"); // NOW set its level. Normally You do not need to set the // level of a logger programmatically. this IS Usually Done // In Configuration Files. Logger.Setlevel (Level.info); Logger Barlogger = Logger.getLogger ("com.foo.bar"); // this request is enabled, Because Warn> = info. logger.warn ("Low Fuel Level."); // This Request Is Disabled, Because Debug Refer to the following table: Remarks of the recorder inherited by the recorder to store the destination Note Root A1 Not Applicable A1 The root logger is anonymous but can be asssed with the logger.getrootlogger () Method. There is no default appender attached to root X A-X1, A-X2 Appenders of "X" and root. XY None True A1, A-X1, A-X2 appenders of "x" and root. xyz A- XYZ1 TRUE A1, A-X1, A-X2, A-XYZ1 appenders in "xyz", "x" and root. security a-secret, since the additivity flag is set to false. security.access NONE TRUE A-Sec Only Appenders of "Security" Because The Additivity Flag in "Security" is set to false. 5, the layout layout is responsible for formatting the LOG information of the output. Log4j's PatternLayout can define formats with formatting templates similar to C language Printf. 6, log4j can automatically provide some log information according to the standards developed by the programmer, which is helpful to the case where the class that needs frequent logs. The object's automatic log has inheritance. The front recorded some principles, today is a practice. 1. The study found that 4% of the code in a system is used to make Logging. 2, log4j's configuration file is used to set the level, regulator, and layout of the logger, which can pick up the setting of the set of key = value format or XML format. By configuration, you can create a log4J's operating environment. Log4J is running, do not do any assumptions for the environment, especially without the default storage. 3, there are several ways to configure log4j1) Call the BasicConfigurator.configure () method in the program; 2) Configure the file name by the command line parameter, parsing and configuring it through PropertyConfigurator.configure ; 3) Configure the file name and other information, by the environment variable, use the log4j default initialization process parsing and configured; 4) Configure the file name and other information, using the application server configuration, using a special servlets to complete the configuration. Look at the following example: Import com.foo.bar; // Import log4j classes.import org.apache.log4j.logger; import org.apache.log4j.basicconfigurator; public class myapp {// define a static logger variable so what it references the // Logger instance named "MyApp" static Logger logger = Logger.getLogger (MyApp.class);. public static void main (String [] args) {// Set up a simple configuration that logs on the console BasicConfigurator.. CONFIGURE (); Logger.info ("Entering Application."); bar bar = new bar (); bar.doot (); logger.info ("exiting application.");}} package com.foo; import ORG. Apache.log4j.logger; public class bar {static logger logger = logger.getlogger (bar.class); public void DOIT () {logger.debug ("DID IT Again!");}}}} BasicConfigurator.configure to Root Recorder Increase a consolerapnder, the output format is set to "% -4R [% T]% -5p% C% X-% M% N", and the default level of the root recorder is Level.debug. The output is as follows: 0 [main] info myapp - Entering application.36 [main] debug com.foo.bar - DID IT AGAIN! 51 [main] info myapp - exiting a The following code combines configuration information, which will result in the same result as the above program. import com.foo.Bar; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class MyApp {static Logger logger = Logger.getLogger (MyApp.class.getName ()); public static void main (String [] args) {// BasicConfigurator replaced with protyconfigurator. PropertyConfigurator.configure (args [0]); Logger.info ("Entering Application)); bar bar = new bar (); bar.doot (); logger The contents of the configuration file are as follows: # set root logger level to debug and it.logger to a1.log4j.rootlogger = debug, A1 # a1 is set to be a consolerappender.log4j. appender.A1 = org.apache.log4j.ConsoleAppender # A1 uses PatternLayout.log4j.appender.A1.layout = org.apache.log4j.PatternLayoutlog4j.appender.A1.layout.ConversionPattern =% - 4r [% t]% -5p % C% X -% M% N uses configuration files that can be easily modified. Following example log4j.rootLogger = debug, stdout, R log4j.appender.stdout = org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout = org.apache.log4j.PatternLayout # Pattern to output the caller's file name and line number. # log4j.appender.stdout.Layout.conversionPattern =% 5P [% T] (% f:% L) -% M% N # print the date in ISO 8601 FormatLog4j.Appender.stdout.Layout.conversionPattern =% D [% T]% -5p% c -% m% nlog4j.rapnder.r = org.apache.log4j.rollingfileAppenderlog4j.Appender.r.file = example.loglog4j.rapnder.r.maxfilesize = 100kb # Keep One Backup filelog4j.Appender. R.maxbackupindex = 1Log4j.Appender.r.Layout = org.apache.log4j.patternlayoutLog4j.Appender.r.Layout.conversionPattern =% P% T% C -% M% N # print Only Messages of Level Warn OR Above in The Package com.foo.log4j.logger.com.foo = WARN For Tomcat4, use environment variables to pass parameters, please refer to the following example UNIX Setting Export Catalina_opts = "- DLOG4J.CONFIGURATION = FOOBAR.TXT" <=== PropertyConfigurator Analysis Export Catalina_opts = "- DLOG4J.DEBUG -DLOG4J.CONFIGURATION = FOOBAR.XML" <=== With DOMCONFIGURATOR, the following is Windows Settings Set Catali NA_OPTS = -Dlog4j.configuration = foobar.lcf -Dlog4j.configuratorClass = com.foo.BarConfigurator <=== parsed set CATALINA_OPTS = -Dlog4j.configuration = file with com.foo.BarConfigurator: / c: /foobar.lcf profile Location If it is not clear, it is necessary to put it in a web-inf / class directory. 4. Configuring the log4j below with the servlet is the article refer to the fire of Ice, and you have made some necessary modifications. It should be noted that the following code needs to write and publish it, there is no such class in JAR. I will write one later and put it up. I also wrote two, in the note (3). Web.xml file in the Application directory Add to code Profiles are as follows: # set root logger level to debug and it has five levels of Logger # Fatal 0 # error 3 # warn 4 # info 6 # debug 7 # Configure root Logger, whose syntax is: # Log4j.rootlogger = [level], appendername, appendername, ... log4j.rootlogger = info, a1, r # This sentence is set to have all logs output # If log4j.rootlogger = Warn, it means that only Warn, Error, Fatal # is output, Debug, INFO will be blocked. # A1 is set to be a consolerappender. # Log4j Appender has several layers such as console, file, GUI components, and even sociable interface servers, NT event logger, UNIX Syslog daemon, etc. #ConsoleAppender output to the console log4j.Appender.a1 = ORG.Apache.log4j.consoleAppender # A1 used output layout, where log4j provides four layouts. Org.apache.log4j.htmlLayout (in HTML form form Layout) # org.apache.log4j.patternLayout (can be flexibly specified) Generated time, thread, category, etc.) log4j.appender.a1.Layout = org.apache.log4j.patternlayout # flexible definition output format View log4j javadoc org.apache.log4j.patternLayout # d Time .... log4j .appender.a1.Layout.conversionPattern =% - D {yyyy-mm-dd hh: mm: ss} [% C] - [% P]% m% N # r Output to the file ROLLINGFILEAPPENDER extension, you can provide one The backup function of the log. Log4j.Appender.r = org.apache.log4j.rollingfileaplender # log file name log4j.Appender.r.file = log4j.log # log file size log4j.Appender.r.maxFileSize = 100kb # Save a backup file log4j. Appender.r.maxbackupindex = 1log4j.appender.r.Layout = org.apache.log4j.tccLayout # log4j.Appender.r.Layout.conversionPattern =% - D {YYYY-MM-DD HH: mm: ss} [% C ] - [% P]% M% N configuration root Logger, its syntax is: log4j.rootlogger = [level], appendername, appendername, ... level is the priority appendername of logging is the specified log information output to which place. You can specify multiple output destinations at the same time. Configuration information log output destination Appender, the syntax is log4j.appender.appenderName = fully.qualified.name.of.appender.classlog4j.appender.appenderName.option1 = value1 ... log4j.appender.appenderName.option = valueN Log4j provided Appender has the following: org.apache.log4j.consoleappender, org.apache.log4j.fileappender (file), org.apache.log4j.dailyRollingFileAppender (a log file is generated every day), org.apache.log4j . RollingFileAppender When a new file is generated when the specified size is specified, or send log information to any specified place in a flow format to any specified place. The syntax is : log4j.appender.appenderName.layout = fully.qualified.name.of.layout.classlog4j.appender.appenderName.layout.option1 = value1 .... log4j.appender.appenderName.layout.option = layout valueN Log4j has provided The following: org.apache.log4j.htmlLayout (layout in HTML table), org.apache.log4j.patternlayout (can be flexibly specified), org.apache.log4j.simplelayout (level and information with log information) String), org.apache.log4j.ttccLayout (including time, thread, category, etc.) I have two programs, one is an ordinary Java program that implements a "nineteen table"; another It is a servlet. I used Tomcat this is 4.1.12, J2se is 1.3.1, the version of log4j is 1.2.8. 1, nine nine table. Environment settings: Need to put log4j-1.2.8.jar into the ClassPath variable. The content of the Hello.java file is as follows: import org.apache.log4j. *; Public class hello {static logger logger = logger.getlogger (Hello.class); public static void main (string [] args) {INT I, J; // BasicConfigurator.configure (); PropertyConfigurator.configure (args [0]); logger.info ("Entering Application."); For (i = 1; i <10; i ) {logger.debug ("" i ); For (j = 1; j <= i; j ) {logger.warn (" j); system.out.print (i * j); system.out.print (" / t ");} System.out.println ("");} logger.info ("EXITING Application.");} Log4j's profile log4j.inf is as follows: log4j.rootlogger = debug, A1, A2 # Record the DAO layer log Davog, if the A2 is removed only to print on the screen # a1 - Print to the screen log4j.appender.a1 = org.apache.log4j.consoleAppenderlog4j.Appender.a1.Layout = Org.apache.log4j.patternlayoutLog4j.PatternlayOutlog4j.Appender .A1.Layout.conversionPattern =% - 5P [% T]% 37C% 3X -% M% N # a2 - Print to file DAOLOG log4j.Appender.a2 = org.apache.log4j.dailyrollingFileAppenderlog4j.Appender.a2. File = phoneLog4j.Appender.a2.datepattern = '.' YYYY-mm-dd'.log'log4j.appender.a2.Layout = Org.apache.log4j.p AtternLayOutlog4j.Appender.a2.Layout.conversionPattern = [% - 5P]% d {YYYY-MM-DD HH: mm: SS, SSS} Method:% L% N% M% N # log4j.category.com.javanew. Components.SMS = Info, A2 # log4j has five Logger #fatal 0 # error 3 #warn 4 #info 6 #debug 7 Note: Generate the log file Phone in the current directory, which does not equal the day when the date will be generated Phone.2003-09-11.log Operation: Javac Hello.javajava Hello log4j.inf results display on the screen and record in the Example.log file. Second, servlet environment settings: Place log4j-1.2.8.jar and servlet.jar into environment variables ClassPath and to copy log4j-1.2.8 to $ Tomcat_home / common / lib directory. Assume that there is a deployment to Tomcat app called myWeb. The content of the servlet program log4jinit.java is in $ TOMCAT_HOME / WebApps / MyWeb / Web-INF / CLASS / COM / HEDONG / LEARNING / LOG4J / Directory, the content is as follows: package com.hedong.Learning.log4j; import org.apache.log4j . *; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Log4jInit extends HttpServlet {public void init () {String prefix = getServletContext () getRealPath. ("/"); String file = GetinitParameter ("log4j"); // if The log4j-init-file is not set, the no point in trying system.out.println ("......... ....... log4j start "); if (file! = null) {propertyconfigurator.configure (prefix file);}} public void doget (httpservletRequest Req, httpservletResponse res) {}} in log4jinit.java Compile it: Javac log4jinit.javamyweb set file Web.xml In the $ TOMCAT_HOME / WebApps / MyWeb / Web-INF / directory, the following red part is added. web-app> ......... http://yourdomain.com:8080/myweb/test/test.jsp, if everything is normal, you will see a big HI. Then, in the $ TOMCAT_HOME / WebApps / dbweb / logs / log4j.log file on the server, you see the following information: Info HttpProcessor [8080] [4] Test.jsp - Befor [8080] [4] Test. JSP - After Say Hi. By default, Tomcat's screen output is redirected to $ Tomcat_home / logs / catalina.out file, and the above output should also be seen in the file. hi h1> <% Logger.info ("After Say Hi");%> then restart Tomcat, access this JSP page via the browser, such as