Log4j User Manual

Source: Internet
Author: User
I. Introduction to log4j Components

A: Three important components of log4j: loggers, appenders, and layouts

These three components work together to enable developers to record information based on information categories and levels, and
During operation, the log storage location has been controlled by the information record method.

B: logger hierarchy)

Almost all APIs that record logs have functions that go beyond the simple system. Out. Print statement. Optional
Select the control output log information, that is, at some time, some log information can be output, and another
The output is not allowed. This assumes that the log record information is classified and defined by the developer.
To classify log information.

The handler name is based on the entity. It has two unique points: (1) it always exists.
(2) It can be retrieved again. You can use the static logger. getrootlogger method of the handler class to obtain it again.
By accessing the static method logger. getlogger, other schedulers are obtained by the instance.
The name of the recorder as the parameter. The methods of some 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 recorder is assigned a level. There is a set of predefined level standards: Debug, info, warn, error and fatal,
These are defined in org. Apache. log4j. Level. You can define your own level standards by inheriting level classes,
This is not encouraged.
If the given recorder is not assigned a level, it will be inherited from the ancestor with the nearest level.
If ancestor is not assigned a level, it inherits from the root recorder. So in general
The recorder can be granted a level, and the recorder will be pre-set. For example, we are operating properties
Log4j. rootlogger = debug, A1. In fact, the root logger and
Root logger level.

* *** Note: the logger level setting makes Logger a choice. If it is set to log_level, logger level
Log_level and lower are output. The lowest priority is Debug. The highest priority is fatal.
# Fatal 0
# Error 3
# Warn 4
# INFO 6
# Debug 7

Appenders

Log4j allows record information to be printed to multiple output destinations. An output destination is called appender. Current log4j
The following output destinations are available: console, file, Gui componennt, and remote socket.
Server, JMS, NT Event logger, and remote UNIX syslog daemons.
Multiple appender can be bound to a logger ).
You can use addappender (logger. addappender) to append an appender to a recorder.
Every valid record request sent to a specific recorder is forwarded to the appender bound to the current recorder.
(Each enabled logging request for a given logger will be forwarded to all the appenders
In that logger as well as the appenders higher in the hierarchy), in other words, appender
Is attached to the recorder hierarchy. For example, if a console appender is bound to the root recorder
(Root logger), all record requests can be printed to the console at least. In addition, appender a file
If it is bound to recorder C, the record requests for recorder C (or descendant of recorder c) can be sent to at least the console appender.
And file appender. Of course, this default behavior can be modified by setting the recorder's additi1_flag.
(Logger. setadditivity) is false, so that the appender does not have additivity ).

Next we will briefly introduce appender additi.pdf.
Appender additivity: the log information recorded by recorder C will be sent to recorder C and its ancestor (ancestor)
All bound appender. However, if the ancestor of recorder C is called P, its additi1_flag is set
False. Then, the record information is still sent to the recorder C and its ancestor, but only to the P level, including P
All the appender of the recorder. But does not include the P ancestor. Generally, the additi1_flag of the recorder is set to true.

Layouts
This section mainly describes the output format. Patternlayout, a standard log4j distributor that allows developers to follow
Conversion patterns defines the output format. Conversion patterns is a bit like a C language printing function.
See the Java properties in the configuration file. The following two lines are displayed:
Log4j. appender. a1.layout = org. Apache. log4j. patternlayout
Log4j. appender. a1.layout. conversionpattern = % d %-5 p [% T] % c {2} (% F: % L)-% m % N
The first row specifies the distributor, and the second row specifies the output format.
For output format definitions, see/org/Apache/log4j/patternlayout.html.

Ii. Configuration
A: Use log4j in Web Application
Step 1:
Configure the log4j configuration file
Log4j. Properties
======================================
# Set root logger level to debug and its only appender to A1
# Log4j has five levels of logger
# Fatal 0
# Error 3
# Warn 4
# INFO 6
# Debug 7
Log4j. rootlogger = debug, A1
# This sentence indicates that all logs are output.
# If it is log4j. rootlogger = warn, A1 means only warn, error, fatal
# Output. debug and info will be blocked.
# A1 is set to be a consoleappender.
# Appender layers in log4j
# Leleappender output to the console
Log4j. appender. A1 = org. Apache. log4j. leleappender

# A1 uses patternlayout.
Log4j. appender. a1.layout = org. Apache. log4j. patternlayout
# For details about the output format, see log4j javadoc org. Apache. log4j. patternlayout.
# D time ....
Log4j. appender. a1.layout. conversionpattern = %-4r [% T] %-5 p % C % x-% m % N

================================ Another configuration
Log4j. rootlogger = debug, stdout, R

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

# Pattern to output the caller's file name and line number.
Log4j. appender. stdout. layout. conversionpattern = % 5 p [% 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 the started Servlet

Public class initservlet extends httpservlet {

Public void Init (){
Servletcontext SCT = getservletcontext ();
String prefix = SCT. getrealpath ("/");
// Log4j configuration file storage 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 according to 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 log4j requires some initialization
This part of initialization is loaded when the appserver starts. In IDE, we are using log4j
You need to configure it yourself before. There are two methods to configure log4j initialization, one is to load the configuration file.
Configure an appender.
The following files:
Public final class lo4jtest {
Private Static string class_name = "com. Bingo. Test. lo4jtest ";
Private Static logger log = logger. getlogger (class_name );
// The 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 ";
// Set the output layer
Private Static string profile = "E:/XML/log4j. properties ";
// Configure according to the 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 );
// Void configure ();
// Log4j provides two methods for configuration.
// The latter is relatively simple, and the output information is not detailed enough.
// We can use the format we want to output the previous one.
// Propertyconfigurator. Configure (profile );
// Configure 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 setting of log4j. properteis in the following line and change debug to error, info, warn, and fatal.
// Different results will be output
// Log4j. rootlogger = debug, A1
}
}

// The Output Using pattern2 is as follows:
13:49:09 [COM. Bingo. Test. lo4jtest]-[debug] log4j debug.
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, the output is 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.]

3. Use log4j
It is actually very simple to use.

1 :) log is defined as follows, and category is used before log4j1.2, and logger is used after log4j1.2
Private Static string class_name = "com. Bingo. Test. lo4jtest ";
// Log4j1.2
Private Static logger log = logger. getlogger (class_name );
// Before lo4j1.2
Private Static category log = category. getinstance (class_name );
// You can obtain a category or logger in several ways.

2 :) write logs
Log. debug ("log4j Debug .");
Log.info ("log4j info .");
Log. Warn ("log4j warn .");
Log. Error ("log4j error .");
Log. Fatal ("log4j fatal .");
// Void debug (Object message)
// Log a message object with the debug level.
// Void debug (Object message, throwable T)
// Log a message object with the debug level including
// Stack trace of the throwable t passed as parameter.

Iv. Notes
1: Pay attention to different log methods for different information. Select debug, error, warn,
One of info and fatal. Some output can be blocked as needed.
2: Try to output the data to the console during development, and modify the configuration during running to output the data to the file.
3: Define the log to use the file name as the parameter as much as possible, so that it is easy to find errors.

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.