--------------------------------------------------------------------------------One: Introduction to LOG4J components
A: log4j three important components--loggers, appenders, Layouts
These three components work together to make it possible for developers to record information based on categories and levels of information, and to be able to run the control of information logging in a way that has been stored in a location.
B: Logger hierarchy (Logger hierarchy)
Almost any log API has functions that go beyond simple System.out.print statements. Allow selective control of output log information, that is to say, some log information allows output, while others do not allow output. This assumes that there is a distinction between log information, which can be categorized according to the selection criteria defined by the developer.
The name of the recorder is based on the entity. It has two unique features: (1) always exists (2) can be rediscovered. Can be logger.getrootlogger by accessing the static method of the class. Other recorders are instantiated or obtained by accessing the static method Logger.getlogger, which takes the name of the logger that you want to get as an argument. Some methods for Logger classes are described as follows: 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); }
The logger is assigned a level, and there is a set of predefined level criteria: DEBUG, INFO, WARN, ERROR and FATAL, which are defined in Org.apache.log4j.Level. You can define your own level criteria by inheriting levels, although this is not encouraged. If a given logger is not assigned a level, it inherits from the ancestor at its nearest owning level. If the ancestor is not assigned a level, it is inherited from the root logger. So in general, in order for all loggers to eventually be assigned a level, the logger will be pre-set. For example, in the operation of the properties file, we will write such a sentence: Log4j.rootlogger=debug, A1. This actually specifies the root Logger and the root Logger level.
Note: The Logger level setting makes Logger a choice, if set to Log_level, then Logger level in the log_level below will be output. The lowest priority is DEBUG. The maximum is FATAL. #FATAL 0 #ERROR 3 #WARN 4 #INFO 6 #DEBUG 7
Appenders
LOG4J allows recording information to be printed to multiple output destinations, and an output destination called Appender. Current log4j existing output destinations include console (console), files (file), GUI componennt,remote Socket server,jms,nt Event logger,and Remote Unix Syslog daemons. Multiple appender can be bound to a logger (Logger). A appender can be attached to a logger by method Addappender (Logger.addappender). Each valid record request sent to a particular logger is forwarded to the Appender that is bound to the current logger. (Each enabled logging request for a given logger would be forwarded to all "appenders in" that logger as "as" the "AppE Nders higher in the hierarchy), in other words, the inheritance hierarchy of Appender is appended to the level of the logger inheritance. For example, if a console appender is bound to the root logger (root Logger), then all record requests can be printed at least to the console. In addition, a file Appender is bound to logger C, and record requests for Logger C (or descendants of C) can be sent at least to the console Appender and file Appender. Of course this default behavior can be changed, by setting the logger additivity flag (logger.setadditivity) to false, so that Appender can no longer have additive (additivity).
Here is a brief introduction to Appender additivity. Appender additivity: Log information logged by logger C will be sent to all appender bound to logger C and its ancestors (ancestor). However, if the ancestor of the recorder C, called P, its additivity flag is set to false. Then, the record information is still sent to the logger C and its ancestors, but only reaches p at this level, including the P-all appender. But does not include the P ancestor. Typically, the additivity flag of the logger is set to true.
Layouts this piece is mainly about the output format. The PATTERNLAYOUT,LOG4J standard allocator allows developers to define output formats according to the conversion patterns. Conversion patterns is a bit like a C-language print function. Refer to the Java properties of the configuration file, such as the following two lines: Log4j.appender.a1.layout=org.apache.log4j.patternlayout log4j.appender.a1.layout.conversionpattern=%d%-5p [%t]%c{2} (%f:%l)-%m%n The first row specifies the allocator, and the second line specifies the format of the output. For a definition of the output format, refer to/org/apache/log4j/patternlayout.html
II: Configuration A: log4j Step 1: Configure log4j profile log4j.properties ========================= # Set root logger le in Web application Vel to DEBUG and it only appender to A1 #log4j中有五级logger #FATAL 0 #ERROR 3 #WARN 4 #INFO 6 #DEBUG 7 Log4j.rootlogg Er=debug, A1 #这一句设置以为着所有的log都输出 #如果为log4j. Rootlogger=warn, A1 means that only warn,error,fatal #被输出, Debug,info will be blocked off. # A1 is set to be a consoleappender. #log4j中Appender有几层 #ConsoleAppender输出到控制台 Log4j.appender.a1=org.apache.log4j.consoleappender
# A1 uses Patternlayout. Log4j.appender.a1.layout=org.apache.log4j.patternlayout #输出格式 specific view of log4j Javadoc org.apache.log4j.PatternLayout #d time ... log4j.appender.a1.layout.conversionpattern=%-4r [%t]%-5p%c%x-%m%n
================================ Another configuration log4j.rootlogger=debug, stdout, R
Log4j.appender.stdout=org.apache.log4j.consoleappender log4j.appender.stdout.layout= Org.apache.log4j.PatternLayout
# to output the caller ' s file name and line number. log4j.appender.stdout.layout.conversionpattern=%5p [%t] (%f:%l)-%m%n #R output to file log4j.appender.r= Org.apache.log4j.RollingFileAppender Log4j.appender.r.file=example.log
LOG4J.APPENDER.R.MAXFILESIZE=100KB # Keep One backup file log4j.appender.r.maxbackupindex=1
Log4j.appender.r.layout=org.apache.log4j.patternlayout log4j.appender.r.layout.conversionpattern=%p%t%c-%m%n
Step 2: Write-Started servlet
public class Initservlet extends HttpServlet {
public void init () {ServletContext SCT = Getservletcontext (); String prefix = Sct.getrealpath ("/"); The log4j configuration file holds the directory System.out.println ("[.... LOG4J]: The Root Path: "+ prefix"; System.out.println ("[...] LOG4J]: Initservlet init start ... "); String file = Getinitparameter ("log4j"); log4j configuration file if (file!= null) {propertyconfigurator.configure (prefix + file); Initialize LOG4J} based on configuration
System.out.println ("[...] LOG4J]: Initservlet Init sucess ... ");
}
public void Doget (HttpServletRequest req, httpservletresponse Res) {
}
public void DoPost (HttpServletRequest req, httpservletresponse Res) {
} }
B: Use log4j in the General IDE, because the log4j needs to do some initialization, in the Web application this part of the initialization is a appserver boot is loaded. In the IDE, we need to configure ourselves before using log4j. There are two ways to configure log4j initialization, one by loading a configuration file. The other is to configure a appender. The following file: Public final class Lo4jtest {private static String class_name = "Com.bingo.test.Lo4jTest"; private static Logger log = Logger.getlogger (class_name); The following pattern in the Web application is configured in the log4j configuration file. Now we manually configure private static String pattern= "%-4r [%-t] [%p] [%c] [%x]-[%m]%n"; private static String pattern2= "%-d{yyyy-mm-dd HH:mm:ss} [%c]-[%p]%m%n"; Sets the output layer private static String profile= "E:/xml/log4j.properties"; Configure by configuration file private static Consoleappender Consappender = new Consoleappender (new Patternlayout (PATTERN2));
public static void Main (string[] args) {//configure log4j basicconfigurator.configure (Consappender); void Configure (Appender appender); void Configure (); When configured log4j provides two ways//after a relatively simple, the output of the information is not detailed//We can use the previous output we want to format//propertyconfigurator.configure (profile); The above is configured according to the configuration file Log.debug ("log4j Debug."); Log.error ("log4j error."); Log.warn ("log4j warn."); Log.info ("log4j info."); Log.fatal ("log4j fatal."); Modify the Log4j.properteis setting to the following line, modify DEBUG to Error,info,warn,fatal//will output different results//log4j.rootlogger=debug, A1}
The output above using PATTERN2 is as follows 2002-08-30 13:49:09 [Com.bingo.test.lo4jtest]-[debug] log4j DEBUG. 2002-08-30 13:49:09 [Com.bingo.test.lo4jtest]-[error] log4j ERROR. 2002-08-30 13:49:09 [Com.bingo.test.lo4jtest]-[info] log4j INFO. 2002-08-30 13:49:09 [com.bingo.test.lo4jtest]-[fatal] log4j FATAL. If we use pattern output as follows: 0 [main] [DEBUG] [com.bingo.test.Lo4jTest] []-[log4j DEBUG.] 0 [main] [ERROR] [com.bingo.test.Lo4jTest] []-[log4j ERROR.] 0 [main] [INFO] [com.bingo.test.Lo4jTest] []-[log4j INFO.] 0 [main] [FATAL] [com.bingo.test.Lo4jTest] []-[log4j FATAL.]
Three: Use log4j in the actual use of the process is actually very simple
1: Define log as follows, use logger instead of private static String class_name = "Com.bingo.test.Lo4jTest" before log4j1.2 use category,log4j1.2; log4j1.2 private static Logger log = Logger.getlogger (class_name); lo4j1.2 formerly private static Category log =category.getinstance (class_name); There are several ways to get a category or logger, depending on what you need to use
2: Write Log log.debug ("log4j Debug."); Log.info ("log4j info."); Log.warn ("log4j warn."); Log.error ("log4j error."); Log.fatal ("log4j fatal."); void Debug (object)//log a message Object with the debug level. void Debug (Object message, Throwable t)//log A and the debug level including the//stack trace of the Throwable t passed as parameter.
Four: NOTE 1: In the specific use of different information to pay attention to the use of different log, select Debug,error,warn, info,fatal in one of the following can be shielded from the need for partial output 2: The development process as far as possible to output to the console, During the run, the configuration is modified to output to the file. 3: Define log as much as possible using file names as parameters, so easy to find errors.
Log4j.properties, put it under the SRC folder.
Log4j.rootlogger=debug, stdout, R
Log4j.appender.stdout=org.apache.log4j.consoleappender
Log4j.appender.stdout.layout=org.apache.log4j.patternlayout
log4j.appender.stdout.layout.conversionpattern=%5p-%m%n
Log4j.appender.r=org.apache.log4j.rollingfileappender
Log4j.appender.r.file=firestorm.log
log4j.appender.r.maxfilesize=100kb
Log4j.appender.r.maxbackupindex=1
Log4j.appender.r.layout=org.apache.log4j.patternlayout
log4j.appender.r.layout.conversionpattern=%p%t%c-%m%n
Log4j.logger.com.codefutures=debug
If you do not need to output debug information, you can change the first line to: Log4j.rootlogger=stdout, R
Source Documents