log4j Introduction
Simply put, log4j is the API class library that helps developers with log output management. The most important feature of it is
You can configure the file to flexibly set the priority of the log information, the output destination of the log information, and the output format of the log information.
log4j In addition to recording the program to run log information, there is also an important function is to display debugging information. Programmers often encounter situations that break out of the Java IDE Environment debugger, when most people choose to use the SYSTEM.OUT.PRINTLN statement to output a variable value method for debugging. This poses a very troublesome problem: once the programmer decides not to display these System.out.println things, it can only be commented out by line. If you need to debug the value of the variable one day, you can only remove these comments in a row to recover the SYSTEM.OUT.PRINTLN statement. Using log4j can be a good treatment for similar situations.
How to use log4j
The following is a description of some of the theoretical aspects of log4j, the readers feel boring can skip this section directly read the third section of the Example section.
1. Define configuration file
Using the configuration file first will make our applications more flexible configure log log output includes output priority, output destination, output format. LOG4J supports two configuration file formats, one in XML format and one for Java attribute file Log4j.properties (key = value). The following describes how to use the Log4j.properties file as a configuration file:
① Configure the root logger with the syntax: 0
Log4j.rootlogger = [level], Appendername, Appendername, ...
Where level is the priority of logging, divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or custom levels. LOG4J recommends using only four levels, from high to low, respectively, for error, WARN, INFO, and DEBUG. By the level defined here, you can control the switch to log information at the appropriate level in your application. For example, if the info level is defined here, all debug-level log information in the application will not be printed. Appendername is where you specify the output of the log information. Multiple output destinations 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.option1 = value1
...
Log4j.appender.appenderName.option = Valuen
Among them, LOG4J provides the following appender:
Org.apache.log4j.ConsoleAppender (console),
Org.apache.log4j.FileAppender (file),
Org.apache.log4j.DailyRollingFileAppender (a log file is generated every day),
Org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the specified size),
Org.apache.log4j.WriterAppender (send log information to any specified place in streaming format)
③ configures the format (layout) of the log information, and its syntax is:
Log4j.appender.appenderName.layout = Fully.qualified.name.of.layout.class
Log4j.appender.appenderName.layout.option1 = value1
...
Log4j.appender.appenderName.layout.option = Valuen
Among them, LOG4J provides the following layout:
Org.apache.log4j.HTMLLayout (layout in HTML form),
Org.apache.log4j.PatternLayout (You can specify layout patterns flexibly),
Org.apache.log4j.SimpleLayout (The level and information string that contains the log information),
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, and so on that the log was generated)
LOG4J uses a print format similar to the printf function in c to format the log information, printing parameters as follows:%m the message specified in the output code
%p output priority, i.e. Debug,info,warn,error,fatal
%r output the number of milliseconds it takes to boot to output the log information
The class to which the%c output 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
%n output a carriage return line feed, Windows platform "", Unix Platform ""
%d output log point-in-time date or time, the default format is ISO8601, you can also specify the format after, such as:%d{yyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28,921
%l the location where the output log event occurs, including the class name, the thread that occurred, and the number of lines in the code. Example: Testlog4.main (testlog4.java:10)
2, the use of log4j in the code
① get the recorder.
Using log4j, the first step is to get the logger, which will be responsible for controlling log information. Its syntax is:
public static Logger GetLogger (String name)
Gets the logger by the specified name and, if necessary, creates a new logger for that name. Name generally takes the names of this class, such as:
static Logger Logger = Logger.getlogger (ServerWithLog4j.class.getName ())
② Read configuration file
When the logger is obtained, the second step configures the LOG4J environment with the following syntax:
Basicconfigurator.configure (): Automatically and quickly uses the default log4j environment.
Propertyconfigurator.configure (String configfilename): Reads a configuration file written using a Java-specific attribute file.
Example: Propertyconfigurator.configure (". \\src\\log4j.properties")
Domconfigurator.configure (String filename): Reads a configuration file in XML form.
③ Insert record information (format log information)
When the two necessary steps are completed, you can easily insert the different priority logging statements into any place you want to log, with the following syntax:
Logger.debug (Object message);
Logger.info (Object message);
Logger.warn (Object message);
Logger.error (Object message);
LOG4J Sample Program
The following is a simple example program to further illustrate how log4j is used. The program code is as follows:
Program Description:
①static Logger Logger = Logger.getlogger (LogTest.class.getName ()); is to create a Logtest object that belongs to the Logger class, When you create, tell logger what your current class is.
②propertyconfigurator.configure ("log4j.properties") means using the log4j.properties file in the SRC folder under the current engineering directory as the configuration file. If you put the log4j.properties in the engineering root directory or do not write this sentence, the program will automatically find the configuration file.
③logger.debug is the output of debug information, Logger.info is the output hint information, Logger.warn is to display a warning message, Logger.error is to display the error message.
The following are the contents of the configuration file log4j.properties:
Program Description:
1. Log4j.rootcategory=debug, Stdout,r
That means I'm going to show all the priority equal to and above debug information.
"stdout", "R" means that I have defined two outputs (whatever name is good).
2. The following three lines say that the stdout output is actually the standard output console, which is the screen. The format of the output is patternlayout. The conversion is%5p (%f:%l)-%m%n, where the first five are used to display precedence, then display the current file name, plus the current number of rows. Finally, the information in Logger.debug () or logger.info () or Logger.warn () or Logger.error (). %n indicates a carriage return blank line.
3. Plus the following six lines log information is not only displayed on the screen, but will be saved in a file called "Log.txt" with a maximum file of 100KB. If the file size exceeds 100KB, the file is backed up as "Log.txt.1", and the new "Log.txt" continues to log the log information.
Next we can change the log4j.properties, without recompiling, we can control whether the log information is displayed, the output type of log information, the output mode, the output format,
Wait a minute. Examples are as follows:
1. Rewrite "log4j.rootcategory=debug,stdout,r" into "Log4j.rootcategory=off, stdout,r" in Log4j.properties file, So all the log information will not be displayed, and solve the problem which the article starts to raise.
2. In the log4j.properties file, rewrite the "Log4j.rootcategory=debug,stdout,r" to "Log4j.rootcategory=info, Stdout,r", which only shows INFO, WARN, Error log information, and debug information will not be displayed;
Using log4j in Web programs attention issues
1. Because the JSP or servlet does not have the current path concept when executing state, all use Propertyconfigurator.configure (String) statement to find the Log4j.properties file to give the path relative to the current JSP or servlet into an absolute file system path. method is to use the Servletcontext.getrealpath (string) statement. Cases:
Get current JSP Path
String prefix = Getservletcontext (). Getrealpath ("/");
Read Log4j.properties
Propertyconfigurator.configure (prefix+\\web-inf\\log4j.properties);
2, the corresponding Log4j.properties set a property when you want to set the absolute path in the program. Cases:
The Log4j.appender.r.file property sets the location where the log files are stored. We can make flexible settings using the method of reading and writing. Properties configuration file.
log4e Use instructions
After understanding the features of log4j, we are sure to write some log4j log records in our program. For programmers using Eclipse, LOG4E will be our most powerful log4j log authoring assistant, and we are now starting our log4e trip.
LOG4E is a free eclipse Plugin that helps you quickly add log to your Java project, and we can download the latest version of log4e on Http://log4e.jayefem.de/index.php/Download Web site. After downloading, copy the appropriate folder to eclipse's plug-in directory, and then eclipse, with one more log4e option in the preferences.
LOG4E can have more than one insert log into a method, class, and of course, you can also insert the log in the current position, and it can also convert Sysout.out.println () to log; All of this just requires you to click the mouse or press the shortcut key,
Configuring log4j in a project in spring
1. Do not place log4j.properties under the root directory of Classpath
When you use JUnit local tests, you will be prompted:
Log4j:warn No Appenders could is found for logger ( Org.springframework.beans.factory.access.SingletonBeanFactoryLocator).
Log4j:warn Please initialize the log4j system properly.
Then we don't see spring loading the Bean's configuration information.
Add: Log4j.properties in the classpath path to display the bean's load information
2. Configure log4j for spring in a Web application
The practice of spring is to use a servlet Listener to write the absolute path of root to the system variable when the Web container is started, so that the log4j configuration file can be ${myappfuse.root} To represent the system variables that have just been set up: Log4j.appender.logfile.file=${myappfuse.root}/logs/mylog.log
The configuration statements in Web.xml are as follows:
<!--if not set, default is Web.root, but best set to avoid conflicts between projects-->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>myappfuse.root</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!--a listener is configured here, or you can configure servlet:-->
<servlet>
<servlet-name>log4j</servlet-name>
<servlet-class>
Org.springframework.web.util.Log4jConfigServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Once configured, we can find the log file in the currently applied logs directory: MyLog.log
The value of the property log4jconfiglocation is recommended or set to:/web-inf/classes/log4j.properties so that we can do some testing to correctly log information when we do not start WEB applications
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.