Look at the Java Web Log trace (3)-log4j usage and configuration

Source: Internet
Author: User
Tags log4j

I have said before about the major use of Java Log Tracking framework, also said, in fact, in which log4j plays a very important role. At present, most of the framework is also the use of log4j, although it has stopped the update, the author also re-logback the project, but Logback currently in the domestic use is quite small. Most of the current projects still use log4j, so record some common usage and configuration of log4j. 1. Simple log4j Use examplelog4j as a better framework, it has a powerful operation of the characteristics of simple, in the daily development process, in fact, the need for developers to do, most of the configuration file is written, rather than to go too much on how to write code. Here's a simple example of using log4j, from which you can see how easy it is to use. first of all, we need to import log4j jar packages, and we will not repeat them here. Then just create the Log4j.properties file in the root directory (which is the file we most often need to write during development), add code to the file
#可以设置级别:debug>info>error#debug: Displays debug, info, Error#info: Display info, error#error: Error only Log4j.rootlogger=Debug,appender1#log4j.rootlogger=Info,appender1#log4j.rootlogger=  error,appender1# output to console log4j.appender.stdout.Threshold=DEBUGlog4j.appender.stdout=  Org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=system.  out log4j.appender.stdout.layout=  Org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=[bash]:%d%5p (%c:%l)-%m%n
Finally, edit the simple test class:
1 Private StaticLogger Logger = Logger.getlogger (Log.class);2 3  Public Static voidMain (string[] args) {4     //System.out.println ("This is println message.");5 6     //record the debug level information7Logger.debug ("This is debug message."));8     //record information at info level9Logger.info ("This is info message."));Ten     //record the error level information OneLogger.error ("This is error message.")); A}


After running, the output on the console is as follows:

[Bash]:2016-01-18 23:10:11,089  info (com.sean.log.logtest1:14)-This is INFO Message[bash]:2016-01-18 23:10:11,093 error (COM.SEAN.LOG.LOGTEST1:15)-This is error message

The above, even if the log4j is completed the simple use. 2, Output what?

Above, we implemented the LOG4J console output, in which there is not much code to use, relatively speaking, need to say is the log4j configuration file. In a common development environment, the use of log4j is focused on the configuration of its configuration files. There are two types of log4j configuration files, one is the properties file and the other is the XML file. Common, but also use the properties of the way to configure.


1. DEBUG (the least serious)
# 2. INFO
# 3. WARN
# 4. ERROR
# 5. FATAL (the most serious)

where the debug level is highest, the fatal level is the lowest, and the higher the defined level, the more levels the log4j output displays, and less. Next, you need to configure the log output class mentioned earlier, tell log4j, which tool class to use output to where, common include like console, text file, HTML file, database and so on. Its configuration is probably as follows
Log4j.appender.appenderName = class# The class used to configure the log output log4j.appender.appendername.key= value# Configuration related log output parameters

To here, for the time being no more how to output, first say what output. In the first instance, it is possible to discover that the output of the console is related to the parameters configured in the configuration file.

in the first instance, a appender is defined as stdout, which is output to the console, where there is a parameter of Conversionpattern, and the instance output information is actually referenced by the template. In log4j , all log4j- defined appender need to define a format output, that is, layout, which uses Patternlayout by default, and layout has a The Conversionpattern parameter is a template that allows developers to configure the information they output. How can it be configured exactly? The parameters include the following:-x:x The information output is left justified;%p: Output log information priority, i.e. Debug,info,warn,error,fatal,%d: The date or time of the output log time, the default format is ISO8601, can also be specified after the format, such as:%d{yyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28, 921%r: The number of milliseconds to output the log information from the application boot to output%c: The class in which the output log information belongs, usually the full name of the class in which it is located%t: Output The name of the thread that generated the log event%l: The location of the output log event, which corresponds to the combination of%c.%m (%f:%l), including the class name, the thread that occurred, and the number of rows in the code. Example: Testlog4.main (testlog4.java:10)%x: The NDC (nested diagnostic environment) associated with the output and current line threads, especially for multi-client multithreaded applications such as Java Servlets. percent: Output a "%" character%F: The name of the file where the output log message was generated%l: Line numbers in the output code%m: The specified message in the output code, resulting in the log specific information%n: Output a carriage return line break, Windows platform is "\ r \ n", Unix platform for "\ n" Output log information line-wrappingadds a modifier between% and the pattern character to control its minimum width, maximum width through the combination of the above parameters, the developer can define what they want to output, with log4j output, such as:%r%5p%d{yyyy-mm-dd HH:mm:ssS}%c%m%n 3. How to Output as mentioned before, log4j can implement output in a variety of ways, including consoles, files, socket,html, databases, and of course, custom output mode. Some of these configurations are only required to be configured in the configuration file, log4j can help us to complete the output, and the socket and database such as the output, it is necessary to the rest of the conditions of the mate to do.
The Following is a more complete log4j configuration file as follows
Log4j.rootlogger=Debug,console,a1,im Log4j.addivity.org.apache=true# applied to console Log4j.appender.CONSOLE=Org.apache.log4j.ConsoleAppender Log4j.appender.Threshold=DEBUG #级别 log4j.appender.CONSOLE.Target=System.out #输出 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout #格式化方式 Log4j.appender.CONSOLE.layout.ConversionPattern=[bash]%d-%c-%-4r [%t]%-5p%c%x-%m%n #格式化标准 #应用于文件 (single file) Log4j.appender.FILE=Org.apache.log4j.FileAppender Log4j.appender.FILE. Threshold=ERROR Log4j.appender.FILE.File=file.log #文件名 log4j.appender.FILE.Append=true#是否累加, is for incremental output, no overwrite output log4j.appender.FILE.layout=org.apache.log4j.PatternLayout #格式化方式 Log4j.appender.FILE.layout.ConversionPattern=[bash]%d-%c-%-4r [%t]%-5p%c%x-%m%N #格式化标准 # use ThisLayout forLogfactor 5Analysis # applied to file increment add, by size Log4j.appender.ROLLING_FILE=Org.apache.log4j.RollingFileAppender #输出类 Log4j.appender.ROLLING_FILE. Threshold=ERROR #输出级别 Log4j.appender.ROLLING_FILE. File=Rolling.log #文件位置, Log4j.appender.ROLLING_FILE can be configured dynamically. Append=true#是否累加, is the increment output, no overwrite output log4j.appender.ROLLING_FILE. MaxFileSize=10KB #文件最大尺寸, Log4j.appender.ROLLING_FILE. Maxbackupindex=1#备份数 log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout #格式化方式 Log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%N # applied to file increment add, by date Log4j.appender.Daily_ROLLING_FILE=org.apache.log4j. dailyrollingfileappender# Output Class Log4j.appender.Daily_ROLLING_FILE. Threshold=ERROR #输出级别 Log4j.appender.Daily_ROLLING_FILE. File=Rolling.log #文件位置, Log4j.appender.Daily_ROLLING_FILE can be configured dynamically. Append=true#是否累加, is for incremental output, no overwrite output log4j.appender.info.DatePattern=-yyyy-mm-dd '. Log 'Log4j.appender.Daily_ROLLING_FILE. Layout=org.apache.log4j.PatternLayout #格式化方式 Log4j.appender.Daily_ROLLING_FILE. Layout. Conversionpattern=[bash]%d-%c-%-4r [%t]%-5p%c%x-%m%N #应用于socket Log4j.appender.SOCKET=Org.apache.log4j.net.SocketAppender log4j.appender.SOCKET.RemoteHost=localhost log4j.appender.SOCKET.Port=5001Log4j.appender.SOCKET.LocationInfo=trueLog4j.appender.SOCKET.layout=org.apache.log4j.PatternLayout Log4j.appender.SOCKET.layout.ConversionPattern=[bash]%d-%c-%-4r [%t]%-5p%c%x-%m%N # Send logs to mail (this way is often blocked with public mailboxes) Log4j.appender.MAIL=Org.apache.log4j.net.SMTPAppenderlog4j.appender.MAIL.Threshold=FATALlog4j.appender.MAIL.BufferSize=10Log4j.appender.MAIL.From= @126. Comlog4j.appender.MAIL.SMTPHost=smtp.126. Comlog4j.appender.MAIL.SMTPUsername= @126. Comlog4j.appender.MAIL.SMTPPassword=Log4j.appender.MAIL.Subject=log4j Messagelog4j.appender.MAIL.To=@qq. Comlog4j.appender.MAIL.layout=Org.apache.log4j.PatternLayoutlog4j.appender.MAIL.layout.ConversionPattern=[bash]%d-%c-%-4r [%t]%-5p%c%x-%m%n# HTML Output Log4j.appender.HTML=Org.apache.log4j.FileAppenderlog4j.appender.HTML.File=d://htmllayout.htmllog4j.appender.html.layout=Org.apache.log4j.HTMLLayoutlog4j.appender.HTML.layout.Title=HTML Layout Examplelog4j.appender.HTML.layout.LocationInfo=trueLog4j.appender.HTML.layout.ConversionPattern=[bash]%d-%c-%-4r [%t]%-5p%c%x-%m%N # for database Log4j.appender.DATABASE=Org.apache.log4j.jdbc.JDBCAppender Log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/testLog4j.appender.database.driver=Com.mysql.jdbc.Driver Log4j.appender.DATABASE.user=Root Log4j.appender.DATABASE.password=Log4j.appender.DATABASE.sql=insert into log4j (Message) VALUES (' [Framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n ') Log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout Log4j.appender.DATABASE.layout.ConversionPattern=[bash]%d-%c-%-4r [%t]%-5p%c%x-%m%n
in the above configuration file, console output, text output, and HTML output are only required to be configured in the configuration file, log4j will be output according to the format in the configuration file. about using the socket output, you need to have a corresponding server, at the same time, the server also needs a server program, socket monitoring, to process the log. For example, when the configuration file is configured as follows:
#应用于socket Log4j.appender.SOCKET=Org.apache.log4j.net.SocketAppender Log4j.appender.SOCKET.RemoteHost=localhost log4j.appender.SOCKET.Port=9090  Log4j.appender.SOCKET.LocationInfo=true  log4j.appender.SOCKET.layout=  Org.apache.log4j.PatternLayout log4j.appender.SOCET.layout.ConversionPattern=[bash]:%d%5p (%c:%l)-%m%n


By default, LOG4J uses the TCP protocol for access, so there is a program on the server side that listens on port 9090 to enable log reception

 public  static  void  Main (String arg[]) throws   IOException {serversocket serversocket  =new  ServerSocket (9090);  while  (true   = serversocket.accept ();        String Line; BufferedReader is  =new  BufferedReader (        New  InputStreamReader (S.getinputstream (), "Utf-8" ));    System.out.println (Is.readline ()); }}
about the way to output by mail, first determine classpath under the Mail.jar package for log4j send use, next need to configure the sending mailbox, and mail server address, as well as user name password. Note that if you are using a mail service provider such as NetEase, such as the mailbox, it is likely to lead to the possibility of sending or interception, while the mail may also have garbled problems. as for the output through the database, first, create a database and table under the corresponding database server as the output object. Next, you need to import the corresponding database-driven jar package, and then configure the user name and password in the configuration file. Finally, configure the database statements that need to be output. Log4j don't know what you need to output, so you need the developer to define the fields to be output, make up the database statements, have log4j to execute, in order to achieve the output of the data. Insert into log (message) values ('%m ')In addition to log4j defined Appender, developers can also customize the way to implement Appender, custom way to inherit the base class Appenderskeleton, concrete how to implement, recommended reference source, here is the main application, will not repeat the at the end of the brief talk about the use of several output modes of log4j, file output should be the most common one, because its configuration is relatively simple, and can be made by date incremental backup, if it is not very high, the method has been able to achieve the purpose of the log output. In contrast, the use of socket,mail relatively less use, first, the use of sockets, the need to have a socket server program to receive logs, which means to add work, unless there is already a corresponding program, otherwise in the development process, The individual does not choose to use the socket. As for mail, the feature is very powerful, but one thing is that if you use a common mail provider, there is the possibility of interception. At the same time, if only when the output of the log is very good, mail will appear in the case, for example, the need to strictly define the standard output error, and then set the mail output level error, if not well set, may cause the continuous sending of junk files possible there are benefits to collecting data in a way that uses databases and HTML. The HTML display of the log is straightforward, but if you use this method alone, you may not be able to further process the log. The most important advantage of using the database is that the log can be processed further, such as indexing, filtering, etc., but the resources required are also more. A good knife to use the blade, the specific how to use, but also according to the specific needs of the design. Reference: http://www.blogjava.net/hwpok/archive/2008/08/23/223891.html

Look at the Java Web Log trace (3)-log4j usage and configuration

Related Article

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.