Document directory
- I. Three Components of log4j
- Ii. Configuration File
In fact, the use of logs is very simple. 1. Import the log4j package, 2. Define the configuration file, and 3. Use it. General steps: Define the log object → read the configuration file → output to the log. That all.
I. Three Components of log4j
Log4j consists of three important components: log priority, appender, and layout.
1. Log priority
From low to high, debug, info, warn, and error are used to specify the importance of the log information. If the input level is defined as info, if the value is equal to or higher than this level, info, warn, and error are entered. It is worth noting that there are two keywords in the level,
ALL: print all logs,
Off: Disable all log output.
2. appender at the output end
Log4j provides the following common output destinations:
Org. Apache. log4j. leleappender to output log information to the console
Org. Apache. log4j. fileappender, which outputs log information to a file
Org. apache. log4j. dailyrollingfileappender outputs the log information to a new log file every day. According to different configurations, you can define a monthly log file, or a weekly, daily, or hourly log file, output A new log file every minute.
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 the stream format.
Org. Apache. log4j. JDBC. jdbcappender: Output log information to the database through JDBC.
Org.apache.log4j.net. smtpappender sends log information to the specified email address. 3. Output Format (layout) Layout
Appender can be used to control the output destination. To control the output format, you can use the layout component of log4j. The configuration file defines the output format of an appender. The layout modes provided by log4j are as follows:
Org. Apache. log4j. leleappender, output to the console
Org. Apache. log4j. htmllayout, in the form of HTML tables
Org. Apache. log4j. patternlayout allows you to flexibly specify the layout mode.
Org. apache. log4j. simplelayout, the log information level and information string are worth mentioning: Org. apache. log4j. patternlayout uses pattern to specify the layout. The format meaning of the conversionpattern parameter is as follows:
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: 2002-10-18-22:10:28; for example, % d {hh: mm: SS, SSS} or % d {dd Mmm yyyy hh: mm: SS, SSS }.
You can refer to Java simpledateformat for the format, but such settings will affect the speed. You can select the faster method % d {iso8601}, % d {absolute}, % d {relative}. Or use the iso8601dateformat, absolutetimedateformat, relativetimedateformat, and datetimedateformat of log4j.
% 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)
% M indicates the method name in the output log.
% 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 indicates the thread name that generates the log event. The configuration file log4j supports two Configuration Methods:. properties binary file and XML file. 1. Define two output modes in the. properties file format. One is output to the file, and the other is output to the database.
First, define the test. properties file, which is defined as follows:
# Two output ends are defined.
Log4j. rootlogger = info, F, DB # defines F to output to a file, and the file increases with the size.
Log4j. appender. f = org. Apache. log4j. rollingfileappender
Log4j. appender. f. File = F: // nepalon // classes // test. Log
Log4j. appender. f. maxfilesize = 512kb
Log4j. appender. f. maxbackupindex = 3
Log4j. appender. f. layout = org. Apache. log4j. patternlayout
Log4j. appender. f. layout. conversionpattern = % d {yyyy-mm-dd hh: mm: SS }:% P % T % C-% m % N # define db output to database
Log4j. appender. DB = org. Apache. log4j. JDBC. jdbcappender
Log4j. appender. DB. buffersize = 40
Log4j. appender. DB. Driver = com. Microsoft. JDBC. sqlserver. sqlserverdriver
Log4j. appender. DB. url = JDBC: Microsoft: sqlserver: // 127.0.0.1: 1433; databasename = test
Log4j. appender. DB. User = sa
Log4j. appender. DB. Password =
Log4j. appender. DB. layout = org. Apache. log4j. patternlayout
Log4j. appender. DB. layout. conversionpattern = insert into log4j (createdate, thread, priority, category, message) values ('% d {iso8601}', '% t',' %-5 ', '% C',' % m') and the configuration file will be referenced in the program. The definition is as follows: Import org. Apache. log4j. Logger;
Import org. Apache. log4j. propertyconfigurator; public class test {
Static logger = logger. getlogger (test. Class. getname (); // defines the log object
Public static void main (string ARGs []) {
Propertyconfigurator. Configure ("test. properties"); // read the configuration file in the property mode.
Logger. debug ("debug"); // output log information to the log
Logger.info ("info ");
Logger. Warn ("Warn ");
Logger. Error ("error ");
Logger. Fatal ("Fatal ");
}
} 2. Configure the program in XML as follows:
Import org. Apache. log4j. Logger;
Import org. Apache. log4j. xml. domaggregator; public class test {
Static logger = logger. getlogger (test. Class. getname (); // defines the log object
Public static void main (string ARGs []) {
Domconfigurator. Configure ("log4jconfig. xml"); // read the configuration file in XML format.
Logger. debug ("debug"); // output log information to the log
Logger.info ("info ");
Logger. Warn ("Warn ");
Logger. Error ("error ");
Logger. Fatal ("Fatal ");
}
} Log4jconfig. XML is as follows: <? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype log4j: Configuration System "log4j. DTD"> <log4j: configuration xmlns: log4j = "http://jakarta.apache.org/log4j/">
<Appender name = "appender" class = "org. Apache. log4j. fileappender">
<Param name = "file" value = "log.txt"/>
<Param name = "APPEND" value = "false"/>
<Layout class = "org. Apache. log4j. patternlayout">
<Param name = "conversionpattern" value = "% d [% T] % P-% m % N"/>
</Layout>
</Appender> <root>
<Priority value = "debug"/>
<Appender-ref = "appender"/>
</Root> </log4j: configuration> compared with the properties and XML methods, we can see that in their programs, apart from defining different ways to read configuration files, there is no difference in other aspects. This is the charm of log4j. without changing the program, you only need to change the defined configuration file to control the log output mode, whether to output the data in the output format. We can control the output mode by defining different XML files.
3. Procedure
1. Import the log4j-1.2.14.jar package in the project
2. Create a log4j configuration file,. properties or. xml file under the SRC package.
3. Procedure
. Usage in applications:
A. Obtain the logger instance: static logger = logger. getlogger (testlog4j. Class );
B. Read the configuration file:
Propertyconfigurator. Configure ("test. properties"); // read the configuration file in the property mode.
Domconfigurator. Configure ("log4jconfig. xml"); // read the configuration file in XML format.
C. Write date:
Logger. debug ("debug"); // output log information to the log
Logger.info ("info ");
Logger. Warn ("Warn ");
Logger. Error ("error ");
Logger. Fatal ("Fatal ");
. Usage in Web Applications
Where should I configure log4j? First, you must make it clear that log4j must complete initialization before other code of the application is executed. Because the servlet is loaded immediately when the web server is started, a special servlet is generally used in web applications to complete log4j configuration and ensure that. in xml configuration, this servlet is located before other servlets. The following is an example of the Code:
A. initialize the configured Servlet
Package com. Foo;
Import org. Apache. log4j. propertyconfigurator;
Import javax. servlet. http. httpservlet;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Import java. Io. printwriter;
Import java. Io. ioexception;
Public class log4jinit extends httpservlet {
Public void Init (){
String prefix = getservletcontext (). getrealpath ("/");
String file = getinitparameter ("log4j-init-file ");
// If the log4j-init-file is not set, then no point in trying
If (file! = NULL ){
Propertyconfigurator. Configure (prefix + file );
}
}
Public void doget (httpservletrequest req, httpservletresponse res ){
}
}
B. Define the following servlet in the web. xml file of your Web Application
<Servlet>
<Servlet-Name> log4j-init </servlet-Name>
<Servlet-class> com. Foo. log4jinit </servlet-class>
<Init-param>
<Param-Name> log4j-init-file </param-Name>
<Param-value> WEB-INF/classes/log4j. properties </param-value>
</Init-param>
<Load-on-startup> 1 </load-on-startup>
</Servlet> C. Obtain the logger instance where log4j is needed
Static logger log = logger. getlogger (testlog4j. Class); D. Write date:
Logger. debug ("debug"); // output log information to the log
Logger.info ("info ");
Logger. Warn ("Warn ");
Logger. Error ("error ");
Logger. Fatal ("Fatal ");