1. Introduction to log4j
Three log objectives:
1. Monitor variable changes in the Code and periodically record the changes to the file for other applications to perform statistical analysis.
2. Tracking the code runtime trajectory as the basis for future audits
3. Act as a debugger in the integrated development environment, and print code debugging information to the file or console.
The most common practice is to embed many print statements into the code, which can be output to the console or file. A good practice is to construct a log operation class to encapsulate such operations, instead of flooding a series of print statements with the subject of the Code.
Apache provides us with a powerful log operation package log4j. By using log4j, we can control the log information delivery destination, including the console, files, Gui components, and even the interface server, NT event recorder, and Unix Syslog daemon; we can also control the output format of each log. By defining the level of each log information, we can control the log generation process in more detail. The most interesting thing is that these can be configured flexibly through a configuration file, without the need to modify the application code.
Ii. Simple Use Cases of log4j
1. Import log4j. jar to the project.
2. Create the log4j. properties file in the project class path (under the SRC folder) as follows (the configuration will be explained later ):
log4j.rootLogger=debug,appender1 log4j.appender.appender1=org.apache.log4j.ConsoleAppender log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout
3. Test code
Package log4j; import Org. apache. log4j. logger; public class log4jtest {Private Static logger = logger. getlogger (log4jtest. class); public static void main (string [] ARGs) {logger. debug ("this is debug message. "); logger. debug ("this is info message. "); logger. debug ("this is error message. ");}}
Output:
[main] DEBUG log4j.Log4jTest - This is debug message. [main] DEBUG log4j.Log4jTest - This is info message. [main] DEBUG log4j.Log4jTest - This is error message.
Iii. Composition of log4j
You can see through the configuration file that there are three main aspects:
- Root directory
- Destination (console, file, etc)
- Output style
Class Diagram of log4j:
Logger-log writer for the programmer to output log information (this is a type that is used in the Program)
Appender-log destination: output formatted log information to the specified location (check the configuration file log4j. properties to understand it)
Leleappender-The appender whose destination is the Console
Fileappender-appender with the object destination
Rollingfileappender-appender where the destination is a file of limited size
Layout-log formatter, used to format the programmer's logging request into a string
Patternlayout-format the layout of the logging request with the specified pattern
4. log4j usage
1. Detailed description of the properties configuration file (log4j supports two configuration file formats: XML and properties (Key = value. The following describes how to use the properties file as the configuration file)
(1) configure the root logger with the Syntax:
Log4j. rootlogger = level, appendername1, appendername2 ,„
Level is the log record priority. We recommend that you use only four levels for log4j. The priority ranges from high to low: error, warn, info, and debug. By defining the level here, you can control the switch to the corresponding level of log information in the application. For example, if the info level is defined here, all debug-level logs in the application will not be printed.
(2) configure the log output destination appender. Its syntax is as follows:
Log4j. appender. appendername = org. Apache. log4j. leleappender log4j. appender. appendername. attribute name (such as layout attribute) = attribute value log4j. appender. appendername. attribute name = Attribute Value
Log4j provides the following types of appender:
- Org. Apache. log4j. leleappender (console)
- Org. Apache. log4j. fileappender (file)
- Org. Apache. log4j. dailyrollingfileappender (a 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 (sends log information in stream format to any specified place
Specific configuration parameters:
1) leleappender options
Threshold = warn: specify the minimum output level of log messages.
- Immediateflush = true: the default value is true, meaning that all messages will be output immediately.
Target = system. Err: system. Out by default, which specifies the output Console
2) fileappender options
Threshold = warn: specify the minimum output level of log messages.
Immediateflush = true: the default value is true, meaning that all messages will be output immediately.
File1_mylog.txt: specify that the message is output to the mylog.txt file.
Append = false: The default value is true. To add a message to a specified file, false means to overwrite the specified file content.
3) dailyrollingfileappender Option
Threshold = warn: specify the minimum output level of log messages.
Immediateflush = true: the default value is true, meaning that all messages will be output immediately.
File1_mylog.txt: specify that the message is output to the mylog.txt file.
Append = false: The default value is true. To add a message to a specified file, false means to overwrite the specified file content.
Datepattern = ''.'' yyyy-ww: The file is rolled every week, that is, a new file is generated every week.
You can also specify monthly, weekly, daily, and hour/minute. The corresponding format is as follows:
1) ''.'' yyyy-MM: monthly
2) ''.'' yyyy-ww: weekly
3) ''.'' yyyy-mm-DD: daily
4) ''.'' yyyy-mm-dd-A: twice a day
5) ''.'' yyyy-mm-dd-hh: Hourly
6) ''.'' yyyy-mm-dd-hh-MM: minute
4) rollingfileappender options
Threshold = warn: specify the minimum output level of log messages.
Immediateflush = true: the default value is true, meaning that all messages will be output immediately.
File1_mylog.txt: specify that the message is output to the mylog.txt file.
Append = false: The default value is true. To add a message to a specified file, false means to overwrite the specified file content.
Maxfilesize = 100kb: The suffix can be kb, MB, or GB. When the log file reaches this size, it will automatically scroll,
Move the original content to the mylog. log.1 file.
Maxbackupindex = 2: specify the maximum number of rolling files that can be generated.
(3) configure the log information format (layout). Its syntax is:
Log4j. appender. appendername. layout = layout class provided by log4j
Log4j provides the following layout types:
Org. Apache. log4j. htmllayout (layout in HTML form)
Org. Apache. log4j. patternlayout (you can flexibly specify the layout mode)
Org. Apache. log4j. simplelayout (Level and string of log information)
Org. Apache. log4j. ttcclayout (including the log generation time, thread, category, and so on)
1) htmllayout options
Locationinfo = true: the default value is false. The Java file name and row number are output.
Title = My app file: The default value is log4j log messages.
2) patternlayout Option
Conversionpattern = % m % N: specify how to format the specified message.
3) xmllayout Option
Locationinfo = true: the default value is false, and the Java file and row number are output.
Log4j uses a print format similar to the printf function in C to format log information. The print parameters are as follows:
og4j.appender.A1.layout.ConversionPattern=%-4r %-5p %d{yyyy-MM-dd HH:mm:ssS} %c %m%n
Here, we need to explain the meanings of several symbols in the log information format:
- -X: left aligned when X information is output;
- % P: Priority of output log information, that is, debug, info, warn, error, fatal,
- % 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 Mmm dd hh: mm: SS, SSS}, output is similar to: October 18, 2002 22:10:28, 921
- % R: The number of milliseconds it takes to output the log information from application startup to application startup.
- % C: the category of the output log. The name in the configuration file is usually the full name of the class (if rootlogger is used)
- % T: name of the thread that outputs the log event
- % L: the location where the output log event occurs. It is equivalent to a combination of % C. % m (% F: % L), including the category name, thread, and number of lines.
- Example: testlog4.main (testlog4.java: 10)
- % X: NDC associated with the current thread (nested Diagnostic Environment), especially for multi-client multithreading applications such as Java Servlets
- In use.
- %: Output A "%" Character
- % F: name of the file in which the output Log message is generated
- % L: the row number in the output code
- % M: output the specific log information of the specified message in the code.
- % N: returns a line break. For Windows, the line break is \ r \ n, for UNIX, and the line feed is \ n.
- % M: Method to which the output log information belongs
You can add modifiers between the % and mode characters to control the alignment of the minimum width, maximum width, and text. For example
1) % 20c: specify the name of the output category. The minimum width is 20. If the category name is smaller than 20, it is right aligned by default.
2) %-20C: specify the name of the output category. The minimum width is 20. If the category name is smaller than 20, the "-" sign specifies the left alignment.
3) %. 30C: specify the name of the output category. The maximum width is 30. If the category name is greater than 30, the extra characters on the left will be truncated, but there will be no spaces if the value is less than 30.
4) % Category 30C: If the category name is less than 20, fill in spaces and align right. If the category name is longer than 30 characters, cut off the characters sold on the left.
2. Use log4j in the code
(1) obtain the recorder
static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName () )
(2) read the configuration file
After obtaining the logger, the second step configures the log4j environment. The syntax is as follows:
Basicconfigurator. Configure (): automatically and quickly use the default log4j environment. Propertyconfigurator. Configure (string configfilename): Read the configuration file written in the Java feature file. Domconfigurator. Configure (string filename): reads configuration files in XML format.
(3) Insert record information (format log information)
When the two necessary steps are completed, you can easily Insert the log record statements with different priorities to any location where you want to record the log. The syntax is as follows:
Logger.debug ( Object message ) ; Logger.info ( Object message ) ; Logger.warn ( Object message ) ; Logger.error ( Object message ) ;
5. properties file instance description
1.
Log4j. rootcategory = info, stdout, r log4j. appender. stdout = org. apache. log4j. leleappender log4j. appender. stdout. layout = org. apache. log4j. patternlayout log4j. appender. stdout. layout. conversionpattern = [QC] % P [% T] % C. % m (% L) | % m % N log4j. appender. R = org. apache. log4j. dailyrollingfileappender log4j. appender. r. file = D :\\ Tomcat 5.5 \ logs \ QC. log log4j. appender. r. layout = org. apache. log4j. patternlayout log4j. AP Pender. r. layout. conversionpattern = % d-[ts] % P % T % C-% m % N log4j.logger.com. neusoft = debug // specify COM. the levels of all classes under the Neusoft package are debug. change Neusoft to the package name used by your project. Log4j.logger.com. opensymphony. Oscache = Error log4j.logger.net. SF. Navigator = Error log4j.logger.org. Apache. commons = Error
2.
### set log levels ###log4j.rootLogger = error,stdout, D, E### \u8f93\u51fa\u5230\u63a7\u5236\u53f0 ###log4j.appender.stdout = org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target = System.outlog4j.appender.stdout.layout = org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%t:%r] - [%p] %m%n### \u8f93\u51fa\u5230\u65e5\u5fd7\u6587\u4ef6 ###log4j.appender.D = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.D.File = ${webapp.root}/logs/log.loglog4j.appender.D.Append = truelog4j.appender.D.Threshold = INFOlog4j.appender.D.layout = org.apache.log4j.PatternLayoutlog4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%t:%r] - [%p] %m%n### \u4fdd\u5b58\u5f02\u5e38\u4fe1\u606f\u5230\u5355\u72ec\u6587\u4ef6 ###log4j.appender.E = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.E.File = ${webapp.root}/logs/error.loglog4j.appender.E.Append = truelog4j.appender.E.Threshold = ERRORlog4j.appender.E.layout = org.apache.log4j.PatternLayoutlog4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss} [%t\:%r] - [%p] %m%n
Use of log4j