First, Introduction
LOG4J is an Apache open source project, by using log4j, we can control the destination of log information delivery is console, file, GUI component, even socket 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.
Log4j consists of three important components: the priority of the log information, the output destination of the log information, and the output format of the log information. The priority of log information is from high to low with error, WARN, INFO, DEBUG, respectively, to specify the importance of this log information; the output destination of the log information specifies whether the log will be printed to the console or the file, and the output format controls the display of the log information .
A good way to use, provide print logs:
# # log4j Settings for log4j 1.2.x (via Jakarta-commons-logging) # # of five logging levels used by Log is (in order): # # 1. DEBUG (The Least serious) # 2. INFO # 3. WARN # 4. ERROR # 5. FATAL (the most serious)
# Set Root logger level to WARN and append to stdout Log4j.rootlogger=debug, stdout log4j.appender.stdout=org.apache.log4j . Consoleappender Log4j.appender.stdout.target=system.out log4j.appender.stdout.layout= Org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
#单条日志的显示格式 log4j.appender.stdout.layout.conversionpattern=%d{yyyy-mm-dd Hh:mm:ss,sss}%p%c.%m (%L):%m%n
# Print only messages of level ERROR or above in the package nomodule. Log4j.logger.nomodule=fatal
# opensymphony Stuff Log4j.logger.freemarker=info Log4j.logger.com.opensymphony=info Log4j.logger.com.opensymphony.xwork2.ognl=error Log4j.logger.org.apache.struts2=warn Log4j.logger.org.apache.struts2.components=warn Log4j.logger.org.apache.struts2.dispatcher=warn Log4j.logger.org.apache.struts2.convention=info # Spring Stuff Log4j.logger.org.springframework=warn
Second, the configuration file
In fact, you can also configure the LOG4J environment in your code without using the configuration file at all. However, using a configuration file will make your application more flexible.
LOG4J supports two configuration file formats, one in XML format and one in the properties format. Here's how to use the properties format as a configuration file:
Example:
Log4j.rootlogger=info, A1
Log4j.appender.a1=org.apache.log4j.consoleappender
Log4j.appender.a1.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.A1.LAYOUT.CONVERSIONPATTERN=%-4R%-5p [%t] 7c%3x-%m%n
1. Configure the root logger, whose syntax is:
Log4j.rootlogger = [level], Appendername, Appendername, ...
in it, level is the priority of logging, which is divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or levels you define. LOG4J recommends using only four levels, priority from high to low is error, WARN, INFO, DEBUG. By defining the level here, you can control the switch to the appropriate level of log information in your application. For example, if the info level is defined here, the log information for all debug levels in the application will not be printed.
Appendername is where you specify where the log information is exported. You can specify multiple output destinations at the same time.
2. Configure the log information output destination Appender, whose 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 types of Appender:
Org.apache.log4j.ConsoleAppender (console),
Org.apache.log4j.FileAppender (file),
Org.apache.log4j.DailyRollingFileAppender (generates a log file every day),
Org.apache.log4j.RollingFileAppender (creates a new file when the file size reaches the specified size),
Org.apache.log4j.WriterAppender (send log information in stream format to any specified location)
(1). Consoleappender Options
Threshold=warn: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
Target=system.err: By default: System.out, specify output console
(2). Fileappender Options
Threshold=warn: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
File=mylog.txt: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with the specified file content.
(3). Dailyrollingfileappender Options
Threshold=warn: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
File=mylog.txt: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with the specified file content.
Datepattern= '. ' YYYY-WW: Scrolls a file once a week, which results in a new file every week. You can also specify monthly, weekly, Days, hours, and minutes. The corresponding format is as follows:
1) '. ' YYYY-MM: Monthly
2) '. ' YYYY-WW: Weekly
3) '. ' YYYY-MM-DD: every day
4) '. ' Yyyy-mm-dd-a: two times a day
5) '. ' YYYY-MM-DD-HH: per hour
6) '. ' YYYY-MM-DD-HH-MM: per minute
(4). Rollingfileappender Options
Threshold=warn: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
File=mylog.txt: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with 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 to move the original content to the Mylog.log.1 file.
maxbackupindex=2: Specifies the maximum number of scroll files that can be produced.
3. Configure the layout of the log information with the following syntax:
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 offers the following types of layout:
Org.apache.log4j.HTMLLayout (Layout in HTML table Form),
Org.apache.log4j.PatternLayout (flexibility to specify layout mode),
Org.apache.log4j.SimpleLayout (contains the level of log information and the information string),
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log
4. Output format settings
The log output format can be set through Log4j.appender.A1.layout.ConversionPattern in the configuration file.
Parameters:
%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-wrapping
You can add modifiers between% and pattern characters to control their minimum width, maximum width, and text alignment. Such as:
1) C: Specify the name of the output category, the minimum width is 20, if the category name is less than 20, the default is the right alignment.
2)%-20c: Specify the name of the output category, the minimum width is 20, if the category name is less than 20, the "-" number specifies left-aligned.
3)%.30c: Specify the name of the output category, the maximum width is 30, if the category name is greater than 30, will be the left more than the character of the cut off, but less than 30, there will be no spaces.
4). 30c: If the category name is less than 20, fill in the blanks, and right-aligned, if its name is longer than 30 characters, it is exported from the left hand-sold characters are truncated.
Third, the use of the program
Before using log4j in your program, first import the Commons-logging.jar and Logging-log4j-1.2.9.jar into classpath and place the log4j.properties in the SRC root directory. Then you can use it.
1. Get the Recorder
Using log4j, the first step is to get the logger, which will be responsible for controlling the log information. Its syntax is:
public static Logger GetLogger (String name),
The logger is obtained by the specified name and, if necessary, a new logger is created for the name. Name generally takes the names of this class, such as:
static Logger Logger = Logger.getlogger (ServerWithLog4j.class.getName ());
Note: commons-logging combined with log4j is recommended for logging
private static Log logger = Logfactory.getlog (Yourclass.class);
2. Inserting record information (formatting log information)
When the two necessary steps are completed, you can easily insert a logging statement with different priority levels 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);
Four, log4j more comprehensive configuration
The simplicity of the log4j configuration allows it to be used in more and more applications: The log4j configuration file implements a full set of functions such as output to console, file, rollback file, send log mail, output to database log table, custom label, etc. The one or two use is enough.
Java code
- 1.log4j.rootlogger=debug,console,a1,im
- 2.log4j.addivity.org.apache=true
- 3.# application to the console
- 4.log4j.appender.console=org.apache.log4j.consoleappender
- 5.log4j.appender.threshold=debug
- 6.log4j.appender.console.target=system.out
- 7.log4j.appender.console.layout=org.apache.log4j.patternlayout
- 8.log4j.appender.console.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n
- 9. #log4j. Appender.console.layout.conversionpattern=[start]%d{date}[date]%n%p[priority]%n%x[ndc]%n%t[thread] N%c [category]%n%m[message]%n%n
- Ten. #应用于文件
- 11.log4j.appender.file=org.apache.log4j.fileappender
- 12.log4j.appender.file.file=file.log
- 13.log4j.appender.file.append=false
- 14.log4j.appender.file.layout=org.apache.log4j.patternlayout
- 15.log4j.appender.file.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n
- 16.# Use this layout for Logfactor 5 analysis
- 17.# Apply to file rollback
- 18.log4j.appender.rolling_file=org.apache.log4j.rollingfileappender
- 19.log4j.appender.rolling_file. Threshold=error
- 20.log4j.appender.rolling_file. File=rolling.log//File location, can also use variable ${java.home}, Rolling.log
- 21.log4j.appender.rolling_file. Append=true//true: Add false: Overwrite
- 22.log4j.appender.rolling_file. MAXFILESIZE=10KB//Maximum file size
- 23.log4j.appender.rolling_file. Maxbackupindex=1//Number of backups
- 24.log4j.appender.rolling_file.layout=org.apache.log4j.patternlayout
- 25.log4j.appender.rolling_file.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n
- 26.
- #应用于socket.
- 28.log4j.appender.socket=org.apache.log4j.rollingfileappender
- 29.log4j.appender.socket.remotehost=localhost
- 30.log4j.appender.socket.port=5001
- 31.log4j.appender.socket.locationinfo=true
- 32.# Set up for Log Facter 5
- 33.log4j.appender.socket.layout=org.apache.log4j.patternlayout
- 34.log4j.appender.socet.layout.conversionpattern=[start]%d{date}[date]%n%p[priority]%n%x[ndc]%n%t[thread]%n%c[ category]%n%m[message]%n%n
- 35.
- 36.# Log Factor 5 Appender
- 37.log4j.appender.lf5_appender=org.apache.log4j.lf5.lf5appender
- 38.log4j.appender.lf5_appender. maxnumberofrecords=2000
- 39.# Send logs to mail
- 40.log4j.appender.mail=org.apache.log4j.net.smtpappender
- 41.log4j.appender.mail.threshold=fatal
- 42.log4j.appender.mail.buffersize=10
- [Email protected]
- 44.log4j.appender.mail.smtphost=www.wusetu.com
- 45.log4j.appender.mail.subject=log4j Message
- [Email protected]
- 47.log4j.appender.mail.layout=org.apache.log4j.patternlayout
- 48.log4j.appender.mail.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n
- 49.# for databases
- 50.log4j.appender.database=org.apache.log4j.jdbc.jdbcappender
- 51.log4j.appender.database.url=jdbc:mysql://localhost:3306/test
- 52.log4j.appender.database.driver=com.mysql.jdbc.driver
- 53.log4j.appender.database.user=root
- 54.log4j.appender.database.password=
- 55.log4j.appender.database.sql=insert into log4j (Message) VALUES (' [Framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n ')
- 56.log4j.appender.database.layout=org.apache.log4j.patternlayout
- 57.log4j.appender.database.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n
- 58.
- 59.log4j.appender.a1=org.apache.log4j.dailyrollingfileappender
- 60.log4j.appender.a1.file=samplemessages.log4j
- 61.log4j.appender.a1.datepattern=yyyymmdd-hh '. log4j '
- 62.log4j.appender.a1.layout=org.apache.log4j.xml.xmllayout
- #自定义Appender.
- 64.log4j.appender.im = Net.cybercorlin.util.logger.appender.IMAppender
- 65.log4j.appender.im.host = Mail.cybercorlin.net
- 66.log4j.appender.im.username = Username
- 67.log4j.appender.im.password = password
- 68.log4j.appender.im.recipient = [email protected]
- 69.log4j.appender.im.layout=org.apache.log4j.patternlayout
- 70.log4j.appender.im.layout.conversionpattern =[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n
Classic summary of log4j configuration, print log file, log repository