log4j use of detailed (finishing)

Source: Internet
Author: User
Tags log4j

1, what is log4j?


Log4j is an open source project for Apache, by using log4j, we can control the destination of log information delivery is console, file, GUI component, even interface server, NT Event recorder, UNIX syslog daemon, etc. We can also control the output format of each log, and by defining the level of each log information, we can control the log generation process more carefully. Most interesting of all, these can be configured flexibly with a single configuration file without the need to modify the applied code. To download and learn more about it, visit its official website: http://jakarta.apache.org/log4j


2, the concept of log4j



The log4j consists of three important components: the logger (loggers), the output end (Appenders), and the log formatter (Layout).


1.Logger: Control which logging statements are enabled or disabled and level the log information


2.Appenders: Specifies whether the log will be printed to the console or file


3.Layout: Control the display format of log information


The log information to be exported in log4j defines 5 levels, in turn, Debug, INFO, WARN, error, and fatal, when the output, only the level of higher than the level specified in the configuration of the information can be true output, so it is convenient to configure different circumstances to output the content, Without the need to change the code, this is really convenient.


a). Acquisition or creation of logger objects


The logger is designated as an entity and is identified by the name of a string class. The name of the logger is case-sensitive, and the name has an inheritance relationship, and the child name is prefixed with the parent name, with the dot "." Separate, for example x.y is X.y.z's father.


Root Logger (Logger) is the ancestor of all Logger, and it has the following properties:


1. It's always there.
2. It may not be obtained by name.


Root logger can be obtained from the following statement:


public static Logger Logger.getrootlogger ();

Or:


public static Logger Logger.getlogger (Class clazz)

The invocation of Logger.getlogger (Class clazz) is the ideal method for the current logger object.


B) Log level


Each logger is logged at a log level to control the output of the log information. Log levels are divided from high to Low:


A:off the highest level, to turn off all log records.
B:fatal that each serious error event will cause the application to exit.
C:error that although an error event occurs, it still does not affect the continued operation of the system.
D:warm indicates a potential error condition.
E:info generally and at a coarse-grained level, emphasize the full application operation.
F:debug is typically used at fine-grained levels and is very helpful for debugging applications.
G:all lowest level to open all log records.


These levels are defined in the Org.apache.log4j.Level class, log4j only 4 levels are recommended, and the priority from highest to lowest is:


1.error

2.warn

3.info

4.debug


By using the logging level, you can control the output of the corresponding level of log information in your application. For example, if you use the info level, all log information, such as debug, that is below the info level in your application will not be printed.


Package log4j;

Import Org.apache.log4j.BasicConfigurator;
Import Org.apache.log4j.Level;
Import Org.apache.log4j.Logger;

public class Log4jtest {public

    static void Main (string[] args) {
        
        Logger Logger = Logger.getlogger (log4jtest.clas s);
        
        Use the default configuration information, do not need to write log4j.properties
        basicconfigurator.configure ();
        Set the log output level to INFO, which overrides the level
        Logger.setlevel (Level.info) set in the configuration file;
        The following message will be output
        logger.info ("This was an info");
        Logger.warn ("This is a Warn");
        Logger.error ("This is a error");
        Logger.fatal ("This is a Fatal");

    }


C) output End Appender


Appender is used to specify where log information is to be 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 add a appender to logger using Logger.addappender (Appender app), or you can use Logger.removeappender (Appender app) Deletes a appender for logger.


The following are several commonly used export 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: Prints log information to a log file and outputs it to a new log file every day.
D:org.apache.log4j.rollingfileappender: Output log information to a log file, and specify the size of the file, when the size of the file reaches the specified size, will automatically rename the file, and create a new file.
E:org.apache.log4j.writeappender: Sends log information to any specified place in streaming format.
F:org.apache.log4j.jdbc.jdbcappender: The log information is exported to the database through JDBC.


D) Log Formatter layout


There are four kinds:


1.HTMLLayout: Format log output as HTML table Form as follows




2.SimpleLayout: Format the log output in a very simple way, it prints three items: level-Information


Example: Info-info


3.PatternLayout: Format the log output according to the specified transformation mode, or use the default transformation mode format if no conversion mode is specified.


The following code implements the Simplelayout and Fileappender programs


public static void Main (string[] args) {
        
        Logger Logger = Logger.getlogger (log4jtest.class);        
        Simplelayout layout = new Simplelayout ();
        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
        Logger.setlevel (level) LEVEL.DEBUG);//overwrite level
        logger.debug ("DEBUG") in the configuration file
        ; Logger.info ("info");
        Logger.warn ("warn");
        Logger.error ("error");
        Logger.fatal ("fatal");
    }


4.TTCCLayout: Contains information about the time, thread, category, etc. of the log generation



3, the log4j configuration


Configuring the log4j environment means configuring root Logger, including which level to Logger, what appender to add to it, and appender for these layout, 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 method of the system properties, or by calling the Xxxconfigurator.configure () method in the program to do it explicitly. There are several ways to configure 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 to resolve and configure.
B: Configuration is placed in the file, through the application server configuration to pass information such as the file meadow, using a specific servlet to complete the configuration.
C: Call the Basicconfigor.configure () method in the program.
D: The configuration is placed in a file and the Log4j.properties file is parsed and configured log4j through the 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 Rootlogger to Dubug;
Rootlogger.setlevel (Level.debug);


Propertyconfigurator.configure () Method:


When the logger object is generated using the following statement:

static Logger Logger = Logger.getlogger (Mycalss.class);

If you do not invoke Basicconfigurator.configure (), propertyconfigurator.configure (), or the Domconfigurator.configure () method, LOG4J automatically loads the configuration file under Classpath named Log4j.properties. If you change this profile to a different name, such as My.properties, the program can still run, but it will report a prompt to initialize the log4j system incorrectly. You can then add the following in your program:


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

Problem can be solved.


4, log4j log4j.properties configuration of detailed


Although it is possible to implement configuration in a program without a configuration file, this approach is clearly undesirable in today's system development, and the configuration file must be used where the configuration file is used. LOG4J supports two types of configuration files: XML format and Java property format.


################################################################################ #① Configuration root logger, its syntax is: # # Log4j.rootlogger = [level],appendername,appendername2,... #level是日志记录的优先级, divided into off,trace,debug,info,warn,error,fatal , all # #Log4j建议只使用四个级别, priority from low to High is Debug,info,warn,error #通过在这里定义的级别, you can control the corresponding level of the application of the log information switch #比如在这里定义了INFO级别, All debug-level log information in the application will not be printed #appenderName就是指定日志信息输出到哪个地方. Multiple output purposes can be specified at the same time ################################################################################ #################### ############################################################ #② Configuration log information output destination Appender, its syntax is: # # 
Log4j.appender.appenderName = Fully.qualified.name.of.appender.class #log4j. Appender.appenderName.optionN = Valuen # #Log4j提供的appender有以下几种: #1) org.apache.log4j.ConsoleAppender (output to console) #2) org.apache.log4j.FileAppender (output to file) #3) Org.apache.log4j.DailyRollingFileAppender (Generate one log file per day) #4) Org.apache.log4j.RollingFileAppender ( When the file size reaches a specified size, a new file is generated #5) Org.apache.log4j.WriterAppender (send log information in streaming format to any specifiedplace) # #1) consoleappender Option Property #-threshold = DEBUG: Specify the lowest level of output for log messages #-immediateflush = true: The default value is true, all messages will be exported immediately #-ta Rget = System.err: Default value System.out, output to console (Err red, out to Black) # #2) fileappender Option Property #-threshold = INFO: Specify the lowest level of output for log messages #-immed Iateflush = true: The default value is true, all messages will be exported immediately #-file = C:\log4j.log: Specify message output to C:\log4j.log file #-append = FALSE: Default value True, append message to specified file , false means to overwrite a message with the specified file content #-encoding = UTF-8: You can specify the file encoding format # #3) dailyrollingfileappender option Properties #-threshold = WARN: Specify the lowest level of output for log messages Times #-immediateflush = true: The default value is true, all messages will be exported immediately #-file = C:\log4j.log: Specify message output to C:\log4j.log file #-append = FALSE: Default value True , appends the message to the specified file, False, which overwrites the message to the specified file content #-datepattern= '. ' YYYY-WW: Scrolls the file once a week, that is, a new file is generated each week. You can also use the following parameters: # '. ' YYYY-MM: Monthly # '. ' YYYY-WW: Weekly # '. ' YYYY-MM-DD: Every day # '. ' Yyyy-mm-dd-a: Two times a day # '. ' YYYY-MM-DD-HH: Every hour # '. ' YYYY-MM-DD-HH-MM: #-encoding per minute = UTF-8: can specify file Encoding format # #4) rollingfileappender option attribute #-threshold = ERROR: Specify the log messageOutput lowest level #-immediateflush = true: The default value is true, all messages will be exported immediately #-file = c:/log4j.log: Specify message output to C:/log4j.log file #-append = FALSE: Default Value true to append the message to the specified file, false means to overwrite the message with the specified file content #-maxfilesize = 100KB: The suffix can be kb,mb,gb. When the log file reaches that size, it will scroll automatically. such as: Log4j.log.1 Maxbackupindex = 2: Specifies the maximum number of scrolling files that can be produced #-encoding = UTF-8: You can specify a file encoding format ################################################### ############################# ################################################################################ #③ Configuration log information Format (layout), whose syntax is: # #log4j. appender.appenderName.layout = fully.qualified.name.of.layout.class # Log4j.appender.appenderName.layout.optionN = Valuen # #Log4j提供的layout有以下几种: #5) org.apache.log4j.HTMLLayout ( Layout in HTML table #6) org.apache.log4j.PatternLayout (can specify layout mode flexibly) #7) Org.apache.log4j.SimpleLayout (level and information string containing log information) #8) Org.apache.log4j.TTCCLayout (including the time, thread, category, and so on) #9) org.apache.log4j.xml.XMLLayout (layout in XML) # #5) htmllayout Option Properties # -locationinfo = TRUE: Default value False, output Java file name and line number #-title=struts log message: Default value log4j log Messages # #6) patternlayout Option Property #-conversionpattern =%m%n: Format specified message (parameter meaning below) # #9) xmllayout Option Property #-locationinfo = TRUE: The default value is False, the output Java file name and line number # #Log4J采用类似C语言中的printf函数的打印格式格式化日志信息, the printing parameters are as follows: #%M The message specified in the output code #%p output priority, that is, Debug,info,warn, Error,fatal #%r Output The number of milliseconds it takes to output the log information from the application the class to which the output belongs, usually the full name of the class, the name of the thread that produces the log event, #%n output a carriage return line break, Windows platform is "\ r \ n", Uni  x platform is "\ n" #%d output log point of date or time, the default format is ISO8601, can also be specified after the format # such as:%d{yyyy mm month DD Day HH:MM:SS,SSS}, output similar: January 05, 2012 22:10:28, 921 # %l the location of the output log event, including the class name, the thread that occurred, and the number of lines in the code # such as: Testlog.main (testlog.java:10) #%F The file name where the output log message was generated #%l line # in output code #%x Output NDC (nested diagnostic environment) associated with the current line threads relative, as in Java servlets Multi-client multithreading application #%% # # # # # can be used to control the minimum width, maximum width, and text alignment between% and pattern characters by adding modifiers. such as: #%5c: Output category name, the minimum width is 5,category<5, the default case of the right alignment #%-5c: Output category name, minimum width is 5,category<5, "-" number specifies left-aligned, there will be space #%.5C : Output category name, the maximum width is 5,category>5, will be left out of the characters, <5 will not have space #%20.30c:category name <20 fill space, and right, >30 characters, I'm going to hand out the characters from the left to cut off the ################################################################################ 
####################################################################### ######### #④ Specifies the output-specific level #log4j of a particular package. Logger.org.springframework=debug ############################################### 
################################# #OFF, Systemout,logfile,logdailyfile,logrollingfile,logmail,logdb,all 
Log4j.rootlogger =all,systemout,logfile,logdailyfile,logrollingfile,logmail,logdb #输出到控制台 Log4j.appender.systemOut = Org.apache.log4j.ConsoleAppender Log4j.appender.systemOut.layout = Org.apache.log4j.PatternLayout Log4j.appender.systemOut.layout.ConversionPattern = [%-5p][%-22d{yyyy/mm/dd hh:mm: 
sss}][%l]%n%m%n Log4j.appender.systemOut.Threshold = DEBUG Log4j.appender.systemOut.ImmediateFlush = TRUE Log4j.appender.systemOut.Target = System.out #输出到文件 log4j.appender.logFile = Org.apache.log4j.FileAppender Log4j.appe Nder.logFile.layout = Org.apache.log4j.PatternLayout Log4j.appender.logFile.layout.ConversionPattern = [%-5p][%-22d {YYYY/MM/DD hh:mm: sss}][%l]%n%m%n log4j.appender.logFile.Threshold = DEBUG Log4j.appender.logFile.ImmediateFlush = TRUE Log4j.appender . Logfile.append = TRUE Log4j.appender.logFile.File =.. 
/struts2/webroot/log/file/log4j_struts.log log4j.appender.logFile.Encoding = UTF-8 #按DatePattern输出到文件 Log4j.appender.logDailyFile = Org.apache.log4j.DailyRollingFileAppender Log4j.appender.logDailyFile.layout = Org.apache.log4j.PatternLayout Log4j.appender.logDailyFile.layout.ConversionPattern = [%-5p][%-22d{yyyy/mm/dd HH: 
mm:sss}][%l]%n%m%n Log4j.appender.logDailyFile.Threshold = DEBUG Log4j.appender.logDailyFile.ImmediateFlush = TRUE Log4j.appender.logDailyFile.Append = TRUE Log4j.appender.logDailyFile.File =.. /struts2/webroot/log/dailyfile/log4j_struts Log4j.appender.logDailyFile.DatePattern = '. ' yyyy-mm-dd-hh-mm '. Log ' log4j.appender.logDailyFile.Encoding = UTF-8 #设定文件大小输出到文件 log4j.appender.logRollingFile = Org. Apache.log4j.RollingFileAppender log4j.appender.logRollingFile.layout = Org.apache.lOg4j. Patternlayout Log4j.appender.logRollingFile.layout.ConversionPattern = [%-5p][%-22d{yyyy/mm/dd hh:mm:sss}][%l]%n%m %n Log4j.appender.logRollingFile.Threshold = DEBUG Log4j.appender.logRollingFile.ImmediateFlush = TRUE Log4j.appender . Logrollingfile.append = TRUE Log4j.appender.logRollingFile.File =.. 
/struts2/webroot/log/rollingfile/log4j_struts.log log4j.appender.logRollingFile.MaxFileSize = 1MB Log4j.appender.logRollingFile.MaxBackupIndex = log4j.appender.logRollingFile.Encoding = UTF-8 #用Email发送日志 Log4j.ap 
Pender.logmail = Org.apache.log4j.net.SMTPAppender Log4j.appender.logMail.layout = org.apache.log4j.HTMLLayout 
Log4j.appender.logMail.layout.LocationInfo = TRUE Log4j.appender.logMail.layout.Title = Struts2 Mail LogFile Log4j.appender.logMail.Threshold = DEBUG Log4j.appender.logMail.SMTPDebug = FALSE Log4j.appender.logMail.SMTPHost = smtp.163.com Log4j.appender.logMail.From = xly3000@163.com log4j.appender.logMail.To = xly3000@gmail.com # Log4j.appender.logmail.cc = xly3000@gmail.com #log4j. appender.logMail.Bcc = xly3000@gmail.com Log4j.appender.logMail.SMTPUsername = xly3000 Log4j.appender.logMail.SMTPPassword = 1234567 log4j.appender.logMail.Subject = log4j Log Messages #log4j. Append Er.logMail.BufferSize = 1024 #log4j. Appender.logMail.SMTPAuth = TRUE #将日志登录到MySQL数据库 Log4j.appender.logDB = Org.apache . log4j.jdbc.JDBCAppender Log4j.appender.logDB.layout = org.apache.log4j.PatternLayout Log4j.appender.logDB.Driver = 
Com.mysql.jdbc.Driver Log4j.appender.logDB.URL = jdbc:mysql://127.0.0.1:3306/xly Log4j.appender.logDB.User = root Log4j.appender.logDB.Password = 123456 LOG4J.APPENDER.LOGDB.SQL = INSERT intot_log4j (project_name,create_date,level, Category,file_name,thread_name,line,all_category,message) VALUES (' Struts2 ', '%d{yyyy-mm-ddhh:mm:ss} ', '%p ', '%c ', ' %F ', '%t ', '%l ', '%l ', '%m '


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.