Java open-source project: a brief introduction to the use of log4j

Source: Internet
Author: User
Source: CCID By dxaw

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 need to import a simple log4j-1.2.x.jar, and then inProgramEnter the following private final static logger log = logger. getlogger (classname. Class) at the beginning of the 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, Set
Log information is output to a file. by specifying the file size, the file will be automatically renamed when the file size reaches the specified size. For example, the file named example. log will be renamed
Example. log.1. A new example. log file is generated at the same time. If the size of the new file reaches the specified size again, the file is automatically renamed
Example. log.2. A example. log file is generated at the same time. 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 outputCodeInformation specified in, 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. leleappender
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 %-5 p-% 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. 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 moment.
. Every time you run logger =
Logger. getlogger (myservlet. Class); generates the E: \ wangzj \ myapplication. log file.

(Responsible editor: Yan Xun)

Link: http://java.ccidnet.com/art/3565/20070702/1130839_1.html


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.