Introduction to log4j

Source: Internet
Author: User
-- By Blues (zhaochaohua@sina.com)
Part 1 Introduction
The advantages of log4j are:
1. By modifying the configuration file, you can determine where the log information is output (console, file,...) and whether it is output.
In this way, you can print detailed log information in the system development phase to track the system operation, and close the log output after the system is stable, so that while tracking the system operation, also reduces the amount of junk code (system. out. println (...) ).
2. Using log4j requires a unified Log Mechanism throughout the system, which is conducive to system planning.

Log4j is easy to use. However, reasonable planning of a system's unified log mechanism requires careful consideration.

For more information about log4j, see the log4j documentation.

Part II configuration file
Let's look at an example of a configuration file:
1. Example of configuration file
[Code] log4j. rootlogger = debug
# Record the DaO layer log to daolog and alllog
Log4j. Logger. Dao = debug, A2, A4
# Record the logic layer log to businesslog and alllog
Log4j. Logger. businesslog = debug, A3, A4
# A1 -- print to the screen
Log4j. appender. A1 = org. Apache. log4j. leleappender
Log4j. appender. a1.layout = org. Apache. log4j. patternlayout
Log4j. appender. a1.layout. conversionpattern = %-5 p [% T] % 37C % 3x-% m % N
# A2 -- print to the file daolog -- specifically for the DaO layer service
Log4j. appender. A2 = org. Apache. log4j. dailyrollingfileappender
Log4j. appender. a2.file = daolog
Log4j. appender. a2.datepattern = '. 'yyyy-mm-dd
Log4j. appender. a2.layout = org. Apache. log4j. patternlayout
Log4j. appender. a2.layout. conversionpattern = [%-5 p] % d {yyyy-mm-dd hh: mm: SS, SSS} method: % L % N % m % N

# A3 -- print to file businesslog -- specifically record the Service Log information of the logic processing layer
Log4j. appender. A3 = org. Apache. log4j. dailyrollingfileappender
Log4j. appender. a3.file = businesslog
Log4j. appender. a3.datepattern = '. 'yyyy-mm-dd
Log4j. appender. a3.layout = org. Apache. log4j. patternlayout
Log4j. appender. a3.layout. conversionpattern = [%-5 p] % d {yyyy-mm-dd hh: mm: SS, SSS} method: % L % N % m % N

# A4 -- print to file alllog -- Record all log information
Log4j. appender. A4 = org. Apache. log4j. dailyrollingfileappender
Log4j. appender. a4.file = alllog
Log4j. appender. a4.datepattern = '. 'yyyy-mm-dd
Log4j. appender. a4.layout = org. Apache. log4j. patternlayout
Log4j. appender. a4.layout. conversionpattern = [%-5 p] % d {yyyy-mm-dd hh: mm: SS, SSS} method: % L % N % m % N [/Code]

2. Use of appender
An appender represents a place where log information is to be written. Log4j can use many types of appender. Here, only three types are considered: leleappender, fileappender, and dailyrollfileappender.
2.1 consoleappender
If consoleappender is used, the log information is written to the console. It directly prints the information to system. Out.
2.2 fileappender
When fileappender is used, log information is written to the specified file. This is often used.
Correspondingly, the log output file name should be specified in the configuration file. The logfile name is demo.txt.
Log4j.appender.a2.file=demo.txt
Replace A2 with the appender alias in the specific configuration.
2.3 dailyrollingappender
Use fileappender to output log information to the file, but it is inconvenient to read the file if it is too large. Then you can use dailyrollingappender. Dailyrollingappender can output log information to files differentiated by date. The following configuration file generates a log file every day. Each log file only records the log information of the current day:

Log4j. appender. A2 = org. Apache. log4j. dailyrollingfileappender
Log4j. appender. a2.file = demo
Log4j. appender. a2.datepattern = '. 'yyyy-mm-dd
Log4j. appender. a2.layout = org. Apache. log4j. patternlayout
Log4j. appender. a2.layout. conversionpattern = % m % N

3. layout Configuration
Layout specifies the log output style.
For more information, see the javadoc of patternlayout.
Example 1: Display date and log information

Log4j. appender. a2.layout = org. Apache. log4j. patternlayout
Log4j. appender. a2.layout. conversionpattern = % d {yyyy-mm-dd hh: mm: SS, SSS} % m % N

The printed information is:
2002-11-12 11:49:42, 866 select * From role where 1 = 1 order by createdate DESC

Example 2: Display date, log location, and log information

Log4j. appender. a2.layout = org. Apache. log4j. patternlayout
Log4j. appender. a2.layout. conversionpattern = % d {yyyy-mm-dd hh: mm: SS, SSS}
% L "#" % m % N

11:51:46, 313 cn.net. unet. weboa. system. Dao. roledao. Select (roledao. Java: 409)
"#" Select * From role where 1 = 1 order by createdate DESC

Example 3: Display Log Level, time, call method, and log information
[Code] log4j. appender. a2.layout = org. Apache. log4j. patternlayout
Log4j. appender. a2.layout. conversionpattern = [%-5 p] % d {yyyy-mm-dd hh: mm: SS, SSS} method: % L % N % m % N
Log information:
[Debug] 12:00:57, 376 method: cn.net. unet. weboa. system. Dao. roledao. Select (roledao. Java: 409)
Select * From role where 1 = 1 order by createdate DESC [/Code]

Part 3 Use of log4j
There are three steps to use log4j:
3. 1. initialize log4j Based on the configuration file
The configuration file is described in Part 2. Now we are talking about how to configure log4j in a program.
Log4j can use the configurator in step 3 to initialize: basicconfigurator, domconfigurator, and propertyconfigurator.
Propertyconfigurator is used here. Propertyconfigurator applies to all systems.
The following statement
Propertyconfigurator. Configure ("log4j. properties ");
The log4j environment has been initialized using log4j. properties as the configuration file.
Note: This statement only needs to be executed once at system startup. For example, this can be used in the unet weboa project:
It is called once in the init () method of actionservlet.

Public class actionservlet extends httpservlet {
...
/**
* Initialize global variables
*/
Public void Init () throws servletexception {
// Initialize the Action Resource
Try {
Initlog4j ();
...
} Catch (ioexception e ){
Throw new servletexception ("load actionres is error ");
}
}
...
Protected void initlog4j (){
Propertyconfigurator. Configure ("log4j. properties ");
}
...
} // End class actionservlet

3.2 obtain the logger instance where log4j is needed
The following is an example of roledao:
Static logger log = logger. getlogger ("Dao ");
Note that the "Dao" identifier is used here. The corresponding configuration information in the configuration file is as follows:

# Define Dao Logger
Log4j. Logger. Dao = debug, A2
# Set attributes of appender A2
Log4j. appender. A2 = org. Apache. log4j. dailyrollingfileappender
Log4j. appender. a2.file = demo
Log4j. appender. a2.datepattern = '. 'yyyy-mm-dd
Log4j. appender. a2.layout = org. Apache. log4j. patternlayout
Log4j. appender. a2.layout. conversionpattern = %-5 p % d {yyyy-mm-dd hh: mm: SS} % L % N % m % N

Public class roledao extends basedbobject
{
...
Static logger log = logger. getlogger ("Dao ");
...
Public beancollection selectall () throws sqlexception
{
Stringbuffer SQL = new stringbuffer (sqlbuf_len );
SQL. append ("select * from" + tablename + "order by roldid ");
// System. Out. println (SQL. tostring ());
Log. debug (SQL );
...
}
...
}

3.3 Use the debug, info, fatal... method of the logger object
Log. debug ("it is the debug info ");

Appendix 1: a bug in log4j
In this case, dailyrollingfileappender cannot be used correctly:

Public class roledao (){

Static logger log = logger. getlogger ("Dao ");

// Execute the configure () operation every time a new roledao object is created.
Public roledao (transactionmanager transmgr) throws sqlexception
{
...
Propertyconfigurator. Configure ("log4j. properties ");
...
}

Public void select (){
...
// Use log4j for log record
Log. debug ("...");
...
}
}

Solution:
Execute propertyconfigurator. Configure ("log4j. properties") at system startup ");
Then, it will not be executed.

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.