Log4j's role: Based on three purposes in the application to add logging in the application: monitoring changes in variables in the code, periodically recorded to other applications for statistical analysis; tracking code runtime trajectory, as The basis of future audits; the action of the debugger in the integrated development environment, prints the debugging information of the code to the file or console.
Log4j's official website: http://logging.apache.org/log4j/docs/
Log4j Basic How Method
Define the configuration file
In fact, you can also use the profile at all, but configure the log4j environment in your code. However, using the profile will make your application more flexible.
Log4j supports two configuration file formats, one is a file in XML format, one is a Java feature file (key = value). Below we describe how to use the Java feature file as a configuration file:
Configure root logger, its syntax is: log4j.rootlogger = [level], appendername, appendername, ... where Level is the priority of log record, divided into OFF, Fatal, Error, Warn, INFO, Debug, All, or you define level. Log4J is recommended to use only four levels, priority from high to low, Error, Warn, Info, Debug. By the level defined here, you can control the switch to the corresponding level of log information in the application. For example, the INFO level is defined here, and all the DEBUG level log information in the application will not be printed. Appendername is where the specified log information is output to which place. You can specify multiple output destinations at the same time. ------ Configure non-root logger, its syntax is: log4j.logger.classpath = [level], appendername, appendername, ... where ClassPath is the class path that log4j can act. If the information of the desire is no longer The parent appears to use the Additive parameter. If log4j.additivity.com.microsoft = false configuration log information output destination Appender, its syntax is log4j.class.Appendername = full.qualified.name.of.Appender.class
Log4j.appender.Appendername.Option1 = value1
...
log4j.appender.appenderName.option = valueN wherein, appender Log4j provided are the following: org.apache.log4j.ConsoleAppender (console), org.apache.log4j.FileAppender (file), org.apache.log4j.DailyRollingFileAppender (Generate a log file per day), org.apache.log4j.rollingFileAppender generates a new file when specified by the specified size, org.apache.log4j.writraPpender (send log information to any specified place in the flow format) ) Format (layout) of log information, whose syntax is: log4j.Appender.Appendername.Layout = Fully.qualified.Name.Of.Layout.class
Log4j.Appender.Appendername.Layout.Option1 = Value1 ...
Layout provided by log4j.Appender.Appendername.Layout.Option = VALUEN, Layout provided by log4j: org.apache.log4j.htmlLayout (layout in HTML form), org.apache.log4j.patternlayout (you can flexibly designate the layout Mode), org.apache.log4j.simplelayout (level, information, org.apache.log4j.ttccLayout (including information, thread, category, etc.)
2. Use log4j in the code
The following will describe how Log4j is used in the program code.
Get recorder
Using log4j, the first step is to obtain a logging device, which will be responsible for control log information. Its syntax is:
Public Static Logger getlogger (String name),
Get the recorder by the specified name, if necessary, create a new recorder for this name. Name generally takes the name of this class, such as:
Static logger logger = logger.getlogger (ServerWithlog4j.class.getname ());
2. Read the configuration file
After the log recorder is obtained, the second step will configure the log4j environment, whose syntax is: BasicConfigurator.configure (): Automatically quickly uses the default Log4j environment. PropertyConfigurator.configure (String configFileName): Read the configuration file written by using the characteristic file using Java. Domconfigurator.configure (String FileName): Read the configuration file in the XML form.
3. Insert the record information (format log information)
When the top two necessary steps are performed, you can easily use different priority logging statements to insert anywhere in the log log, whose syntax is as follows: logger.debug (Object Message);
Logger.info (Object Message);
Logger.warn (Object Message);
Logger. Error (Object Message);
Log4J Application Example first download the package address from the ASF (Apache Source forge): http://logging.apache.org/log4j/docs/download.html puts the log4j-1.2.9.jar under the Dist directory to you Let JDK loads under ClassPath. Now try the call to the WEB program. 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 ("" " ("exiting application.");}} This program requires a parameter (Arg [0]), creating its configuration file name log4j.inf reference: log4j.rootlogger = warn, stdout, rlog4j .appender.stdout = org.apache.log4j.consolerappenderlog4j.consolerappenderlog4j.Appender.stdout.Layout = org.apache.log4j.patternlayoutLog4j.Appender.stdout.Layout.conversionPattern =% D [% T]% -5p% C -% M% nlog4j.appender.R = org.apache.log4j.RollingFileAppenderlog4j.appender.R.File = $ {user.dir} example.loglog4j.appender.R.MaxFileSize = 100KBlog4j.appender.R.MaxBackupIndex = 1log4j.appender.R. Layout = org.apache.log4j.patternLayoutLog4j.Appender.r.Layout.conversionPattern =% P% T% C -% M% NLOG4J.Logger.com.foo = WARN Now run Java Hello Log4j.inf and see if there is any example.log, OK, and the test is successful. Then look at the call of the web. Since logs need to record days throughout the application. Therefore, it needs to start when the project is loaded, and the specific content is to load its configuration parameters.
First, write a servlet, let him load when the project is loaded, parsing log4j.properties. Reference is as follows: package com.mdcl.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-init- File "); // if the log4j-init-file is not set, the no point in tryingsystem.out.println (" ................ log4j start "); if (! file = null) {PropertyConfigurator.configure (prefix file);}} public void doGet (HttpServletRequest req, HttpServletResponse res) {}} log4j.properties reference to the following: log4j.rootLogger = ERROR, R # log4j.appender.A1 = org.apache.log4j.consoleappender # log4j.appender.a1.Layout = org.apache.log4j.patternLayout # log4j.Appender.a1.Layout.conversionPattern =% - D {yyyy-mm-dd hh: mm: ss} [% c] - [% P]% m% n log4j.Appender.r = org.apache.log4j.rollingfileAppenderLog4j.Appender.r.file = d: /tomcat5/webapps/six/logs/log4j.loglog4j.ap Pender.r.maxfilesize = 100kblog4j.rapnder.r.maxbackupindex = 1Log4j.Appender.r.Layout = org.apache.log4j.patternlayoutLog4j.Appender.R.Layout.conversionPattern =% P% T% C -% M% N pairs Web.xml makes the following modification:
Page Import Org.Apache.log4j.logger;%>
this is my jsp page.Below is a few points of log4j:
1. Hierarchical naming: If a logger's name follows a point (Dot), it is the Logger's predecessor after the point (DOT), which is the prefix of this undendant. If there is no other predecessor in itself and this toilet, it is a father and child relationship with this jade. 2. Level inherits For a given Logger C, the level of inherits is equal to the first non-Null level of the root logger from the root logger from the Logger class. 3. Execute the rules in a Logger at a level of Q (specified or inherited), a log request for a P> P> q can be executed. 4. Appender Additive Rule
Logger C's log output information will be output to all appenders and its senior Appenders. This is the meaning of "appender additivity". However, if Logger C's predecessors, such as P, P, the Additive Flag is set to false, then the output information of C will be output to all Aprenders in C, and its seniors - deadlines, Including P is, here, there is not to output it in the appenders of the Seniors of the P. By default, Loggers' additive flag is set to True. About the log format: Post a sample:
Log4j.Appender.a1.Layout.conversionPattern =% D% -5P [% T]% -C (% 13F:% L)% 3X -% M% N
See http://www.jaxwiki.org/en/project/logging.apache.org/log4j/docs/Manual.html