Log4j using Notes

Source: Internet
Author: User

Log4j is an open source project for Apache. By using log4j, programmers can control the destination of log information delivery, including consoles, files, GUI components, and NT event loggers, and can control the output format of each log, or control the log generation process more carefully by defining the level of each log message. The following code is an example:

//log4j
PublicvoidLog4jdemo ()
{
Logger Logger = Logger.getlogger (Test.class);

FileReader FR =NULL;
Try
{
FR = new filereader ("Info.txt");
Logger.info ("Begin read File");
}
Catch(FileNotFoundException e)
{
Logger.error ("File not Found", e);
Try{
Fr.close ();
}Catch(IOException E1){

Logger.error ("File not Found", E1);
}
}
}

The composition of log4j:
The log4j consists of three important components: the logger (loggers), the output (appenders), and the log formatter (layout).
Logger: Controls which logging statements are enabled or disabled, with a level limit on log information: appenders Specifies whether the log will be printed to the console or the file, and layout controls the display format of the log information.

A). Logger the acquisition or creation of an object :
Logger is specified as an entity and is identified by the name of a string class. Logger's name is case sensitive, and the name has an inheritance relationship, and the child name is prefixed with the parent name, using the dot "." Separated, for example x.y was the father of x.y.z.
Root Logger (root Logger) is the ancestor of all Logger, and it has the following properties:
1. It's always there.
2. It cannot be obtained by name.
Root logger can be obtained using the following statement:

PublicStaticLogger Logger.getrootlogger ();

Or:

PublicStaticLogger Logger.getlogger (Class clazz)

Calling Logger.getlogger (Class clazz) is the ideal method for Ogger objects at this time.

B) log level
Each logger is logged at a log level to control the output of the log information. The log level is divided from high to Low:
A:off the highest level for closing all log records.
B:fatal indicates that each serious error event will cause the application to exit.
C:error points out that although an error event occurs, it still does not affect the system's continued operation.
D:warm indicates that a potential error condition occurs.
E:info general and at the coarse-grained level, the application is emphasized throughout the run.
F:debug is generally used for fine-grained levels and is very helpful for debugging applications.
G:all the lowest level to open all log records.

The above levels are defined in the Org.apache.log4j.Level class. Log4j only recommends using 4 levels, with priority levels from high to low for Error,warn,info and debug respectively. By using the log level, you can control the output of the appropriate level of log information in your application. For example, if you use the info level B, all log information (such as Debug) in your application that is below the info level will not be printed.

Packagelog4j;

ImportOrg.apache.log4j.BasicConfigurator;
ImportOrg.apache.log4j.Level;
ImportOrg.apache.log4j.Logger;

PublicclassLog4jtest{

PublicStatic voidMain (string[] args){

Logger Logger = Logger.getlogger (log4jtest.class);

//using the default configuration information, do not need to write log4j.properties
Basicconfigurator.configure ();
//set the log output level to info, which overrides the level set in the configuration file
Logger.setlevel (Level.info);
//the following message will be output
Logger.info ("This was an info");
Logger.warn ("This is a warn");
Logger.error ("This was an error");
Logger.fatal ("This is a Fatal");

}

}

C) output End Appender
The appender is used to specify where the log information is exported and multiple output destinations can be specified at the same time. LOG4J allows information to be exported to many different output devices, and a log information output destination is called a appender.
Each logger can have one or more appender, and each appender represents the output destination of a log. You can use Logger.addappender (Appender app) to add a Appender to logger, or you can use Logger.removeappender (Appender app) Deletes a appender for logger.
The following are some common output destinations for log4j.
A:org.apache.log4j.consoleappender: Output log information to the console.
B:org.apache.log4j.fileappender: Output log information to a file.
C:org.apache.log4j.dailyrollingfileappender: Output log information to a log file and output to a new log file daily.
D:org.apache.log4j.rollingfileappender: Output log information to a log file, and specify the size of the file, when the file size reaches the specified size, will automatically rename the file, and generate a new file.
E:org.apache.log4j.writeappender: Sends the log information in stream format to any specified place.
F::org.apache.log4j.jdbc.jdbcappender: Output log information to the database through JDBC.

Log Formatter layout
There are three kinds:
Htmllayout: Formatted log output as HTML table Form:
Simplelayout: Format the log output in a very simple way, it prints three items: level-Information
Example: Info-info
Patternlayout:: Formats the log output according to the specified conversion mode, or uses the default conversion mode format if no conversion mode is specified.
The following code implements the Simplelayout and Fileappender programs

PublicStatic voidMain (string[] args){

Logger Logger = Logger.getlogger (log4jtest.class);
Simplelayout layout =NewSimplelayout ();
//htmllayout layout = new Htmllayout ();
Fileappender Appender =NULL;
Try
{
// Configure the output to OUT.txt
Appender = new fileappender (layout, "OUT.txt",false);
}Catch(Exception e)
{
}
Logger.addappender (Appender);//Add output side
Logger.setlevel (level) level.debug);//overriding levels in a configuration file
Logger.debug ("Debug");
Logger.info ("info");
Logger.warn ("warn");
Logger.error ("error");
Logger.fatal ("fatal");
}

configuration of the log4j
Configuring the log4j environment means configuring root Logger, including which level to Logger, which appender to add, and layout for these appender, and so on. Because all other logger are descendants of root logger, they all inherit the nature of root logger. These can be done implicitly by setting the system properties, or you can call the Xxxconfigurator.configure () method in your program to do so explicitly. There are several ways to configure the log4j.
A: The configuration is placed in the file, through the environment variables to pass the file name and other information, using the LOG4J default initialization process parsing and configuration.
B: The configuration is placed in the file, through the application server configuration to pass the file, such as the meadow, using a specific servlet to complete the configuration.
C: Call the Basicconfigor.configure () method in the program.
D: The configuration is placed in the file, and the Log4j.properties file is parsed and configured log4j via command line Propertyconfigurator.configure (args[]).
The Basicconfigurator.configure () method and the Propertyconfigurator.config () method are described below respectively.
basicconfigurator.configure () method:
It uses a simple method to configure the log4j environment. The tasks that this method accomplishes are:
1: Create the Patternlayout object P in the default way:
Patternlayout p = new Patternlayout ("%-4r[%t]%-5p%c%x-%m%n");
2: Create Consoleappender object A with P, Target is system.out, standard output device:
Consoleappender a = new Cpnsoleappender (p,consoleappender.system_out);
3: Add a consoleappender p for root logger;
Rootlogger.addappender (P);
4: Set the log level of the Rootlogger to Dubug;
Rootlogger.setlevel (Level.debug);

propertyconfigurator.configure () method :
When you use the following statement to generate a logger object:

StaticLogger Logger = Logger.getlogger (MYCALSS.class);

If you do not call the Basicconfigurator.configure (), propertyconfigurator.configure (), or Domconfigurator.configure () method, LOG4J automatically loads the configuration file named Log4j.properties under Classpath. If you change this profile to a different name, such as My.properties, the program still works, but it will report a hint that the log4j system could not be initialized correctly. This can be added in the program:

Propertyconfigurator.configure ("Classes/my.properties");

Problem can be solved.


LOG4J application examples in the log4j use notes do not write an instance, then in this article I will log4j a complete application example written out.
Inlog4j Using NotesWe already know that the same log information can be output to multiple output destinations at the same time. In the example below, I will demonstrate the output of log information to both the console, the file, and the database. First create a table, as follows:
CREATE TABLE log4j (    logid int not NULL auto_increment,--serial number    createdate varchar) default NULL,--log generation time    Thread varchar default NULL,--current thread    level varchar default NULL,--current log Levels    class varchar default NULL, --Generate Log class    message varchar (245) default NULL,--log specific information        primary key (Logid))


Writing a configuration file mylog4j.properties

#定义3个输出端
Log4j.rootcategory=info,a1,a2,a3

#定义A1输出到控制器
Log4j.appender.a1=org.apache.log4j.consoleappender
#定义A1的布局模式为PaternLayout
Log4j.appender.a1.layout=org.apache.log4j.patternlayout
# define the output format of the A1
log4j.appender.a1.layout.conversionpattern=%4p [%t] (%f:%l)-%m%n

#定义A2输出到文件
Log4j.appender.a2=org.apache.log4j.rollingfileappender
#定义A2输出到哪个文件
Log4j.appender.a2.file=./sample.log
#定义A2输出文件的最大长度
Log4j.appender.A2.MaxFileSize = 1KB
#定义A2的备份文件数
Log4j.appender.A2.MaxBackupIndex = 3
#定义A2的布局模式为PatternLayout
Log4j.appender.a2.layout=org.apache.log4j.patternlayout
#定义A2的输出模式
LOG4J.APPENDER.A2.LAYOUT.CONVERSIONPATTERN=%D{YYYY-MM-DD hh:mm:ss}:%p%t%c-%m%n

#定义A3输出到数据库
Log4j.appender.a3=org.apache.log4j.jdbc.jdbcappender
Log4j.appender.a3.url=jdbc:mysql://localhost:3306/study
Log4j.appender.a3.driver=com.mysql.jdbc.driver
Log4j.appender.a3.user=root
Log4j.appender.a3.password=root
#定义A3的布局和执行的SQL语句
Log4j.appender.a3.layout=org.apache.log4j.patternlayout
Log4j.appender.a3.layout.conversionpattern=insert into log4j (createdate,thread,level,class,message) VALUES (\ '%d\ ' , \ '%t\ ', \ '%-5p\ ', \ '%c\ ', \ '%m\ ')


The final test procedure is as follows: PublicStaticvoidSample ()
{
Logger Logger = Logger.getlogger (log4jtest. Class);

Propertyconfigurator.configure ("Mylog4j.properties");
Logger.debug ("Here is Debug Messgae");
Logger.info ("Here is info message");
Logger.warn ("Here is warn message");
Logger.error ("Here is the error message");
Logger.fatal ("Here is fatal message");
}That way, when we run the program, we're going to turn the log information into three places at the same time:
Console:

Database:

File:

we have seen the Sample.log file, which we specified in the configuration, of course you can also modify other places, the other log4j configuration files are also placed in the project root directory.
at the same time, when we run the program more than a few times, Sample.log more than 1KB will automatically rename the file, and then log to the new Sample.log fileAs follows:

This paper draws on: http://www.cnblogs.com/eflylab/archive/2007/01/12/618080.html

Copyright NOTICE: Welcome reprint, Hope in your reprint at the same time, add the original address, thank you with

Log4j using Notes

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.