A Brief Introduction to the use of log4j

Source: Internet
Author: User

I. Preface

There are too many open-source projects in Java, and this everywhere will definitely catch up with the flourishing of "Hundred Schools of contention" and "Hundred Flowers of Competition" in China's five-generation Ten-Nation period. Using Java technology, we almost do not need to buy Java-supported development products for our projects. We only need to combine and splice an open-source product with the hands of architects, you can make commercial products with excellent flexibility and good performance.

Undoubtedly, as a popular logging tool, log4j is one of the brightest links in Java open-source projects. The Java project I have seen uses log4j in. The reasons are as follows:

A) log4j is supported by most web application servers: As far as I know, tomcat, WebLogic, websphere, and JBoss support log4j.

B) fast and powerful functions: the log4j configuration file provides a full set of functions such as output to the console, files, rollback files, sending log emails, outputting to database log tables, and custom tags. In terms of speed, since the beginning of log4j, the speed of running has always been at the top, and constant improvements and improvements have been made.

C) Easy to use: Just import a simple log4j-1.2.x.jar, and then write the following sentence at the beginning of the program class private final static logger log = logger. getlogger (classname. Class );

In this way, you get a log object log, which can easily write logs to a specific target.

2. Why do I need log4j? --- Project debugging is the internal driving force generated by log4j

The original method is to output the information to the console and use the system. Out. println provided by JDK. However, the disadvantage of doing so is obvious:

A) information output is not flexible enough and tedious. For example, the file name, number of lines, and current time at the execution place to be output, println looks very primitive.

B) If you want to change the output content and format, you need to re-compile the source program.

C) More seriously, if the program contains many println, it will seriously affect the program performance.

Iii. How many key points does log4j use?

Logger, appenders, and layouts)

A) The format of the root recorder is defined

Log4j. rootlogger = [level], appendname1, appendname2 ,... Appendnamen. The same recorder can have multiple output ports.

PS: Level (this level can be customized. The system provides the following levels by default)

◆ Debug // debug information

◆ Info // General information

◆ Warn // warning information

◆ Error // error message

◆ Fatal // fatal error message

The above lists the output levels of log4j. We recommend that you use only four levels: error, warn, info, and debug from top to bottom. Assume that the defined level is info, the logs of error and warn can be displayed, but the debug information lower than him will not be displayed.

B) define the output destination format of an appender

Log4j. appender. appendername = fully. Qualified. Name. Of. appender. Class. Log4j provides the following common output destinations:

◆ Org. Apache. log4j. leleappender: Output log information to the console

◆ Org. Apache. log4j. fileappender: Output log information to a file

◆ Org. Apache. log4j. dailyrollingfileappender: output the log information to one and output it to a new log file every day.

◆ Org. apache. log4j. rollingfileappender: outputs log information to a file. by specifying the file size, the file is automatically renamed when the file size reaches the specified size, for example, example. the log file will be renamed as example. log.1 and generate a new example. log File. If the size of the new file reaches the specified size again, the file is automatically renamed as example. log.2, and a example. log file is generated. Wait until example. log. maxbackupindex. The value of maxbackupindex can be defined in the configuration file.

◆ Org. Apache. log4j. writerappender: sends log information to any specified place in stream format.

◆ Org. Apache. log4j. JDBC. jdbcappender: Output log information to the database through JDBC.

C) Output Format (layout) Layout

Log4j provides the following la s:

◆ Org. Apache. log4j. htmllayout, which is displayed as an HTML table

◆ Org. Apache. log4j. patternlayout, You can flexibly specify the layout mode

◆ Org. Apache. log4j. simplelayout, which contains the log information level and information string

The statement that defines a patternlayout layout is:

Log4j. appender. stdout. layout = org. Apache. log4j. patternlayout

Log4j. appender. stdout. layout. conversionpattern = % d {absolute} % 5 P % c {1}-% m % N

PS: Format meaning of the conversionpattern Parameter

Format name meaning

% C full name of the class to which the output log information belongs

% D date or time of the log output time point. The default format is iso8601. You can also specify the format after it, for example, % d {YYY-mm-dd hh: mm: SS}, output is similar to:-22:10:28

% F Class Name of the class to which the output log information belongs

% L location where the log event is output, that is, the number of lines in the class where the statement that outputs the log information is located

% M output the specified information in the Code, such as the message in log (Message)

% N output a carriage return line break. For Windows, the value is/R/N, and for UNIX, the value is/n"

% P output priority, that is, debug, info, warn, error, fatal. If it is output by calling debug (), it is debug, and so on.

% R the number of milliseconds it takes to output the log information from application startup to output.

% T name of the thread that outputs the log event

4. log4j configuration file: log4j. properties or log4j. xml

A) There are several ways to configure log4j

◆ Call the basicconfigurator. Configure () method in the program;

◆ Put the configuration in the file, pass the file name through command line parameters

Propertyconfigurator. Configure (ARGs [x]) Parse and configure;

◆ Put the configuration in the file, pass the file name and other information through the environment variable, and parse and configure the configuration using the default initialization process of log4j;

◆ Put the configuration in a file, pass the file name and other information through the application server configuration, and use a special servlet to complete the configuration.

B) configuration file initialization:

Initialize the Application Server

Complete initialization with Servlet assistance

C) Example of a log4j. properties File


      
       log4j.rootLogger=INFO, stdout, logfile
       
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=/webserver/specialTraining3/wangzj.log
log4j.appender.logfile.MaxFileSize=51200KB
log4j.appender.logfile.MaxBackupIndex=3
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - <%m>%n

5. Use log4j for an example

Test:

Com. webage. servlets. myservlet

Log4j. properties file:


      
       log4j.rootLogger=DEBUG,ROOT
       
log4j.appender.ROOT=org.apache.log4j.RollingFileAppender
log4j.appender.ROOT.File=E:/wangzj/myapplication.log
log4j.appender.ROOT.MaxFileSize=1000KB
log4j.appender.ROOT.MaxBackupIndex=5
log4j.appender.ROOT.layout=org.apache.log4j.PatternLayout
log4j.appender.ROOT.layout.ConversionPattern=[%d]%t%c%-5p-%m%n
ootLogger=DEBUG,CONSOLE,A1,im
log4j.addivity.org.apach

Mymodel. Java file:


      
       
Package com. webage. model;
       
Import org. Apache. log4j. Logger;
Public class mymodel {
Static logger = logger. getlogger (mymodel. Class );;
Public void checkvalid (string name, string value) throws exception {
Logger. debug ("entry ");
Logger. debug ("Check parameter:" + name );
If (value = NULL ){
Throw new exception ("the parameter is missing. ");
}
If (value. Trim (). Length () = 0 ){
Throw new exception ("parameter is null. ");
}
Logger. debug ("exit ");
}
}

Myservlet. Java


      
       
Package com. webage. servlets;
       
Import java. Io. ioexception;
Import javax. servlet. servletexception;
Import javax. servlet. http. httpservlet;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Import org. Apache. log4j. Logger;
Import com. webage. model. mymodel;
Public class myservlet extends httpservlet {
Logger logger = logger. getlogger (myservlet. Class );
Public void doget (httpservletrequest req, httpservletresponse resp)
Throws servletexception, ioexception {
Logger. debug ("entry ");
Mymodel model = new mymodel ();
Resp. getwriter (). println ("log4j test ");
Try {
Model. checkvalid ("firstname", req. getparameter ("firstname "));
} Catch (exception e ){
Logger. Error ("doget error.", e );
}
Logger. debug ("exit ");
}
Public void Init () throws servletexception {
Super. INIT ();
Logger.info ("servlet initialization ...");
}
}

Two jar packages are required: servlet. jar and log4j-1.2.9.jar.

Ready to run in Tomcat or weblogic. I will use WebLogic for the time being. Every time you run logger = logger. getlogger (myservlet. Class); the E:/wangzj/myapplication. log file is generated.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.