log4j configuration File Detailed explanation

Source: Internet
Author: User
Tags custom name

I. Introduction of LOG4J

The log4j has three main components: loggers (Logger), appenders (output source), and layouts (layout). This can be simply understood as the log category, where the logs are to be exported and how the logs are exported. The combined use of these three components makes it easy to record the type and level of information, and to control the style and location of the log output at run time.

1, loggers

The loggers component is divided into five levels in this system: DEBUG, INFO, WARN, error, and fatal. These five levels are sequential, DEBUG < INFO < WARN < ERROR < FATAL, respectively, to specify the importance of this log information, it is important to understand this, log4j has a rule: output level is not lower than the set level of log information, Assuming that the loggers level is set to info, the log information for info, WARN, error, and fatal levels is output, and debug with a lower level than info will not be output.

2, Appenders

Disabling and using log requests is just the basic function of log4j, and the log4j log system also provides many powerful features, such as allowing logs to be exported to different places, such as consoles, files, etc., which can generate new files depending on the number of days or the size of the file. Can be sent to other places in the form of streams and so on.

The following classes are commonly used:

Org.apache.log4j.ConsoleAppender (console)
Org.apache.log4j.FileAppender (file)
Org.apache.log4j.DailyRollingFileAppender (Generate 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)

Configuration mode:
Log4j.appender.appenderName = ClassName
Log4j.appender.appenderName.Option1 = value1
...
Log4j.appender.appenderName.OptionN = Valuen

3, Layouts

Sometimes users want to format their own log output according to their preferences, log4j can be appended to the appenders layouts to complete this function. Layouts provides four types of log output, such as styles based on HTML styles, free-to-specify styles, styles that contain log levels and information, and information that contains log time, threads, categories, and so on.

The following classes are commonly used:

Org.apache.log4j.HTMLLayout (Layout in HTML table Form)
Org.apache.log4j.PatternLayout (flexibility to specify layout mode)
Org.apache.log4j.SimpleLayout (contains level and information strings for log information)
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log

Configuration mode:

Log4j.appender.appenderName.layout =classname
Log4j.appender.appenderName.layout.Option1 = value1
...
Log4j.appender.appenderName.layout.OptionN = Valuen

Second, configuration detailed

In the actual application, in order to make the log4j run in the system, the configuration file must be set beforehand. The configuration file is, in fact, the logger, Appender, and layout are set accordingly. LOG4J supports two configuration file formats, one in XML format and the Properties property file. The following is an example of the configuration of the log4j.properties with the Properties property file.

1. Configure Root logger:
Log4j.rootlogger = [level], appenderName1, appenderName2, ...
Log4j.additivity.org.apache=false: Indicates that logger does not output in the appender of the parent logger, which is true by default.
Level: Sets the lowest levels of logging, the values that can be set are off, FATAL, ERROR, WARN, INFO, DEBUG, all, or custom levels, and LOG4J recommends using only the middle four levels. By setting the level here, you can control the switch of the appropriate level of log information in the application, such as setting the info level here, and the log information for all debug levels in the application will not be printed.
Appendername: Specifies where the log information is to be exported. You can specify multiple output destinations at the same time, separated by commas.
Example: LOG4J.ROOTLOGGER=INFO,A1,B2,C3

2. Configure the log information output destination (Appender):
Log4j.appender.appenderName = ClassName
Appendername: Custom Appdername, used in Log4j.rootlogger settings;
ClassName: The following values can be set:
(1) Org.apache.log4j.ConsoleAppender (console)
(2) org.apache.log4j.FileAppender (file)
(3) Org.apache.log4j.DailyRollingFileAppender (Generate a log file every day)
(4) Org.apache.log4j.RollingFileAppender (creates a new file when the file size reaches the specified size)
(5) Org.apache.log4j.WriterAppender (send log information in stream format to any specified location)
(1) Consoleappender options:
Threshold=warn: Specifies the minimum output level for log information, which is debug by default.
Immediateflush=true: Indicates that all messages will be output immediately, set to False to not output, and the default value is true.
Target=system.err: The default value is System.out.
(2) Fileappender options:
Threshold=warn: Specifies the minimum output level for log information, which is debug by default.
Immediateflush=true: Indicates that all messages will be output immediately, set to False to not output, and the default value is true.
Append=false:true indicates that the message was added to the specified file, false overwrites the message with the specified file content, and the default value is true.
FILE=D:/LOGS/LOGGING.LOG4J: Specifies that the message is output to the logging.log4j file.
(3) Dailyrollingfileappender options:
Threshold=warn: Specifies the minimum output level for log information, which is debug by default.
Immediateflush=true: Indicates that all messages will be output immediately, set to False to not output, and the default value is true.
Append=false:true indicates that the message was added to the specified file, false overwrites the message with the specified file content, and the default value is true.
FILE=D:/LOGS/LOGGING.LOG4J: Specifies that the current message is output to the logging.log4j file.
Datepattern= '. ' YYYY-MM: Scrolls the log file once a month, resulting in a new log file per month. The log file name for the current month is logging.log4j, and the first one months of the log file name is logging.log4j.yyyy-mm.
Alternatively, you can specify that the log files be scrolled by week, day, time, minute, and so on in the following format:
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 minimum output level for log information, which is debug by default.
Immediateflush=true: Indicates that all messages will be output immediately, set to False to not output, and the default value is true.
Append=false:true indicates that the message was added to the specified file, false overwrites the message with the specified file content, and the default value is true.
FILE=D:/LOGS/LOGGING.LOG4J: Specifies that the message is output to the logging.log4j file.
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 logging.log4j.1 file.
maxbackupindex=2: Specifies the maximum number of scrolling files that can be generated, for example, set to 2 to produce logging.log4j.1,logging.log4j.2 two scrolling files and a logging.log4j file.

3. Configuration log information output format (Layout):
Log4j.appender.appendername.layout=classname
ClassName: The following values can be set:
(1) Org.apache.log4j.HTMLLayout (Layout in HTML table Form)
(2) Org.apache.log4j.PatternLayout (flexibility to specify layout mode)
(3) Org.apache.log4j.SimpleLayout (contains the level of log information and information string)
(4) Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log
(1) Htmllayout options:
Locationinfo=true: Output Java file name and line number, the default value is False.
Title=my Logging: The default value is log4j Log Messages.
(2) Patternlayout options:
conversionpattern=%m%n: Sets the format in which messages are displayed.

Format Symbol Description:

%p: The priority of the output log information, which is debug,info,warn,error,fatal.
%d: the date or time of the output log time, the default format is ISO8601, or the format can be specified later, such as:%d{yyyy/mm/dd hh:mm:ss,sss}.
%r: The number of milliseconds to output the log information from the application startup to output.
%t: Outputs the name of the thread that generated the log event.
%l: The location of the output log event, equivalent to the%c.%m (%f:%l) combination, including the class name, method, file name, and number of rows in the code. For example: Test. Testlog4j.main (testlog4j.java:10).
%c: The output log information belongs to the class, which is usually the full name of the class.
%M: Outputs the method name that produces the log information.
%F: The name of the file where the output log message was generated.
%l:: The line number in the output code.
%m:: The specific log information specified in the output code.
%n: Output a carriage return line break, the Windows platform is "\ r \ n" and the UNIX platform is "\ n".
%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: Outputs a "%" character.
In addition, you can also add modifiers between% and format characters to control their minimum length, maximum length, and text alignment. Such as:
1) C: Specify the name of the output category, the minimum length is 20, if the category name length is less than 20, the default is the right alignment.
2)%-20c: "-" indicates left alignment.
3)%.30c: Specify the name of the output category, the maximum length is 30, if the category name length is greater than 30, will be the left more than the character of the cut off, but less than 30 will not fill the space.

Attached: log4j more comprehensive configuration

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.
Log4j.rootlogger=debug,console,dailyfile,im
Log4j.additivity.org.apache=true
# Consoles (console)
Log4j.appender.console=org.apache.log4j.consoleappender
Log4j.appender.console.threshold=debug
Log4j.appender.console.immediateflush=true
Log4j.appender.console.target=system.err
Log4j.appender.console.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.CONSOLE.LAYOUT.CONVERSIONPATTERN=[%-5P]%d (%r)--[%t]%l:%m%x%n

# log file (LogFile)
Log4j.appender.logfile=org.apache.log4j.fileappender
Log4j.appender.logfile.threshold=debug
Log4j.appender.logfile.immediateflush=true
Log4j.appender.logfile.append=true
log4j.appender.logfile.file=d:/logs/log.log4j
Log4j.appender.logfile.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.LOGFILE.LAYOUT.CONVERSIONPATTERN=[%-5P]%d (%r)--[%t]%l:%m%x%n
# rollback file (rollingfile)
Log4j.appender.rollingfile=org.apache.log4j.rollingfileappender
Log4j.appender.rollingfile.threshold=debug
Log4j.appender.rollingfile.immediateflush=true
Log4j.appender.rollingfile.append=true
log4j.appender.rollingfile.file=d:/logs/log.log4j
log4j.appender.rollingfile.maxfilesize=200kb
Log4j.appender.rollingfile.maxbackupindex=50
Log4j.appender.rollingfile.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.ROLLINGFILE.LAYOUT.CONVERSIONPATTERN=[%-5P]%d (%r)--[%t]%l:%m%x%n
# Roll back log files periodically (Dailyfile)
Log4j.appender.dailyfile=org.apache.log4j.dailyrollingfileappender
Log4j.appender.dailyfile.threshold=debug
Log4j.appender.dailyfile.immediateflush=true
Log4j.appender.dailyfile.append=true
log4j.appender.dailyfile.file=d:/logs/log.log4j
Log4j.appender.dailyfile.datepattern= '. ' Yyyy-mm-dd
Log4j.appender.dailyfile.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.DAILYFILE.LAYOUT.CONVERSIONPATTERN=[%-5P]%d (%r)--[%t]%l:%m%x%n
# Applied to Socket
Log4j.appender.socket=org.apache.log4j.rollingfileappender
Log4j.appender.socket.remotehost=localhost
log4j.appender.socket.port=5001
Log4j.appender.socket.locationinfo=true
# Set up for Log Factor 5
Log4j.appender.socket.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.SOCKET.LAYOUT.CONVERSIONPATTERN=[%-5P]%d (%r)--[%t]%l:%m%x%n
# Log Factor 5 Appender
Log4j.appender.lf5_appender=org.apache.log4j.lf5.lf5appender
Log4j.appender.LF5_APPENDER. maxnumberofrecords=2000
# send log to specified message
Log4j.appender.mail=org.apache.log4j.net.smtpappender
Log4j.appender.mail.threshold=fatal
log4j.appender.mail.buffersize=10
Log4j.appender.mail.From = [email protected]
Log4j.appender.mail.smtphost=mail.com
Log4j.appender.mail.subject=log4j Message
log4j.appender.mail.to= [email protected]
Log4j.appender.mail.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.MAIL.LAYOUT.CONVERSIONPATTERN=[%-5P]%d (%r)--[%t]%l:%m%x%n
# Apply to Database
Log4j.appender.database=org.apache.log4j.jdbc.jdbcappender
Log4j.appender.database.url=jdbc:mysql://localhost:3306/test
Log4j.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 (' =[%-5p]%d (%r)--[%t]%l:%m%x%n ')
Log4j.appender.database.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.DATABASE.LAYOUT.CONVERSIONPATTERN=[%-5P]%d (%r)--[%t]%l:%m%x%n

# Custom Appender
log4j.appender.im = Net.cybercorlin.util.logger.appender.IMAppender
Log4j.appender.im.host = Mail.cybercorlin.net
Log4j.appender.im.username = Username
Log4j.appender.im.password = password
log4j.appender.im.recipient = [email protected]
Log4j.appender.im.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.IM.LAYOUT.CONVERSIONPATTERN=[%-5P]%d (%r)--[%t]%l:%m%x%n


The power of log4j is undeniable, but the actual application inevitably encountered a function need to output a separate log file, how can you separate the required content from the original log to form a separate log file? In fact, as long as the existing log4j based on a little configuration can easily achieve this function.

First look at a common log4j.properties file, which is logging in the console and the Myweb.log file:

Log4j.rootlogger=debug, stdout, logfile
Log4j.category.org.springframework=error
Log4j.category.org.apache=info


Log4j.appender.stdout=org.apache.log4j.consoleappender
Log4j.appender.stdout.layout=org.apache.log4j.patternlayout
log4j.appender.stdout.layout.conversionpattern=%d%p [%c]-%m%n

Log4j.appender.logfile=org.apache.log4j.rollingfileappender
Log4j.appender.logfile.file=${myweb.root}/web-inf/log/myweb.log
log4j.appender.logfile.maxfilesize=512kb
Log4j.appender.logfile.maxbackupindex=5
Log4j.appender.logfile.layout=org.apache.log4j.patternlayout
log4j.appender.logfile.layout.conversionpattern=%d%p [%c]-%m%n
  

If you want to output different files for different classes (take cn.com.Test as an example), first define them in Test.java:

private static Log logger = Logfactory.getlog (Test.class);

Then add in the Log4j.properties:

Log4j.logger.cn.com.test= DEBUG, Test
Log4j.appender.test=org.apache.log4j.fileappender
Log4j.appender.test.file=${myweb.root}/web-inf/log/test.log
Log4j.appender.test.layout=org.apache.log4j.patternlayout
log4j.appender.test.layout.conversionpattern=%d%p [%c]-%m%n

That is, let the logger in cn.com.Test use the configuration made by Log4j.appender.test.

But what if you need to output multiple log files in the same class? In fact, the truth is the same, first defined in Test.java:

private static Log Logger1 = Logfactory.getlog ("MyTest1");
private static Log Logger2 = Logfactory.getlog ("MyTest2");

Then add in the Log4j.properties:

log4j.logger.mytest1= DEBUG, Test1
Log4j.appender.test1=org.apache.log4j.fileappender
Log4j.appender.test1.file=${myweb.root}/web-inf/log/test1.log
Log4j.appender.test1.layout=org.apache.log4j.patternlayout
log4j.appender.test1.layout.conversionpattern=%d%p [%c]-%m%n

Log4j.logger.mytest2= DEBUG, Test2
Log4j.appender.test2=org.apache.log4j.fileappender
Log4j.appender.test2.file=${myweb.root}/web-inf/log/test2.log
Log4j.appender.test2.layout=org.apache.log4j.patternlayout
log4j.appender.test2.layout.conversionpattern=%d%p [%c]-%m%n

That is, when using logger, give it a custom name (such as "MyTest1"), and then make the appropriate configuration in log4j.properties. Don't forget to use different logger for different logs (e.g., to use Logger1.info ("abc") for output to Test1.log).
Another problem is that these custom logs are exported to the logs configured by Log4j.rootlogger at the same time, how can they only be output to their own specified log? Don't worry, there's a switch here:

Log4j.additivity.myTest1 = False

It is used to set the output to the Log4j.rootlogger configured log, false will not output to other places! Note that the "MyTest1" here is the custom name you gave logger in the program!

If you say, I just do not want to output this log at the same time Log4j.rootlogger configured logfile, stdout I also want to output it at the same time! That's good, put your log4j.logger.myTest1 = DEBUG, test1 change to the next type on OK!
Log4j.logger.mytest1=debug, Test1

log4j configuration File Detailed explanation

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.