Log4j configuration details, log4j details

Source: Internet
Author: User
Tags custom name

Log4j configuration details, log4j details

1. Introduction to Log4j

Log4j has three main components: Loggers, Appenders, and Layouts ). This can be simply understood as the log category, where the log is to be output, and in what form the log is output. Using these three components together, you can easily record the types and levels of information and control the log output style and position at runtime.

1. Loggers

Loggers components in this system are divided into five levels: DEBUG, INFO, WARN, ERROR, and FATAL. These five levels are ordered. DEBUG <INFO <WARN <ERROR <FATAL is used to specify the importance of the log information. To understand this, Log4j has a rule: only log information of the level not lower than the set level is output. If the Loggers level is set to INFO, logs of the INFO, WARN, ERROR, and FATAL levels are output, DEBUG with a lower level than INFO will not be output.

2. Appenders

Disabling and using log requests is only a basic function of Log4j. The Log4j log system also provides many powerful functions, such as allowing logs to be output to different places, such as the Console) files, such as Files, can generate new Files based on the number of days or file size, can be sent to other places in the form of a stream, and so on.

The frequently used classes are as follows:

Org. apache. log4j. leleappender (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 stream format)

Configuration Mode:
Log4j. appender. appenderName = className
Log4j. appender. appenderName. Option1 = value1
...
Log4j. appender. appenderName. OptionN = valueN

3. Layouts

Sometimes you want to format your log output according to your preferences. Log4j can add Layouts to the Appenders to complete this function. Layouts provides four types of log output styles, such as HTML styles, custom styles, styles that contain log levels and information, and styles that contain log time, threads, and categories.

The frequently used classes are as follows:

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 other information)

Configuration Mode:

Log4j. appender. appenderName. layout = className
Log4j. appender. appenderName. layout. Option1 = value1
...
Log4j. appender. appenderName. layout. OptionN = valueN

Ii. configuration details

In practical applications, configuration files must be set in advance for Log4j to run in the system. The configuration file is actually set for Logger, Appender, and Layout. Log4j supports two configuration file formats: XML and properties. The following uses the properties file as an example to introduce the configuration of log4j. properties.

1. Configure the root Logger:
Log4j. rootLogger = [level], appenderName1, appenderName2 ,...
Log4j.additivity.org. apache = false: indicates that Logger will not be output in the appender of the parent Logger. The default value is true.
Level: set the minimum log record level. The value can be OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL, or custom level. Log4j recommends only four levels in the middle. By setting the level here, you can control the switch of log information of the corresponding level in the application, for example, setting the INFO level here, all DEBUG-level logs in the application will not be printed.
AppenderName: specifies where the log information is to be output. Multiple Output destinations can be specified at the same time, separated by commas.
Example: log4j. rootLogger = INFO, A1, B2, C3

2. Configure the log output destination (appender ):
Log4j. appender. appenderName = className
AppenderName: Custom appderName, used in log4j. rootLogger settings;
ClassName: The configurable values are as follows:
(1) org. apache. log4j. leleappender (console)
(2) org. apache. log4j. FileAppender (file)
(3) org. apache. log4j. DailyRollingFileAppender (a log file is generated every day)
(4) org. apache. log4j. RollingFileAppender (a new file is generated when the file size reaches the specified size)
(5) org. apache. log4j. WriterAppender (send log information to any specified place in stream format)
(1) leleappender options:
Threshold = WARN: specify the minimum log output level. The default value is DEBUG.
ImmediateFlush = true: indicates that all messages are output immediately. If it is set to false, no messages are output. The default value is true.
Target = System. err: The default value is System. out.
(2) FileAppender options:
Threshold = WARN: specify the minimum log output level. The default value is DEBUG.
ImmediateFlush = true: indicates that all messages are output immediately. If it is set to false, no messages are output. The default value is true.
Append = false: true indicates that the message is added to the specified file. If false, the message overwrites the content of the specified file. The default value is true.
File = D:/logs/logging. log4j: Specify the message output to the logging. log4j File.
(3) DailyRollingFileAppender options:
Threshold = WARN: specify the minimum log output level. The default value is DEBUG.
ImmediateFlush = true: indicates that all messages are output immediately. If it is set to false, no messages are output. The default value is true.
Append = false: true indicates that the message is added to the specified file. If false, the message overwrites the content of the specified file. The default value is true.
File = D:/logs/logging. log4j: specify that the current message is output to the logging. log4j File.
DatePattern = '. 'yyyy-MM: the log file is rolled every month, that is, a new log file is generated every month. The log file name for the current month is logging. log4j, and the log file name for the previous month is logging. log4j. yyyy-MM.
In addition, you can specify weekly, daily, hourly, and grading to scroll the log file. 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 log output level. The default value is DEBUG.
ImmediateFlush = true: indicates that all messages are output immediately. If it is set to false, no messages are output. The default value is true.
Append = false: true indicates that the message is added to the specified file. If false, the message overwrites the content of the specified file. The default value is true.
File = D:/logs/logging. log4j: Specify the message output to the logging. log4j File.
MaxFileSize = 100KB: The suffix can be KB, MB, or GB. When the log file reaches this hour, it will automatically scroll, moving the original content to the logging. log4j. 1 file.
MaxBackupIndex = 2: specify the maximum number of rolling files that can be generated. For example, if set to 2, logging can be generated. log4j. 1. logging. log4j. 2. Two Rolling files and one logging. log4j file.

3. Configure the log output format (Layout ):
Log4j. appender. appenderName. layout = className
ClassName: The configurable values are as follows:
(1) org. apache. log4j. HTMLLayout (layout in HTML form)
(2) org. apache. log4j. PatternLayout (you can flexibly specify the layout mode)
(3) org. apache. log4j. SimpleLayout (Level and information string containing log information)
(4) org. apache. log4j. TTCCLayout (including the log generation time, thread, category, and other information)
(1) HTMLLayout options:
LocationInfo = true: Name and row number of the output java file. The default value is false.
Title = My Logging: The default value is Log4J Log Messages.
(2) PatternLayout options:
ConversionPattern = % m % n: set the format of the message to display.

Format symbol description:

% P: Priority of the output log information, namely DEBUG, INFO, WARN, ERROR, and FATAL.
% D: date or time of the log output time point. The default format is ISO8601. You can also specify the format after this, for example, % d {yyyy/MM/dd HH: mm: ss, SSS }.
% R: The number of milliseconds it takes to output the log information from application startup.
% T: name of the thread that generates 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 class full name, method, file name, and number of lines in the code. For example, test. TestLog4j. main (TestLog4j. java: 10 ).
% C: the category of the output log, usually the full name of the class.
% M: name of the method that outputs log information.
% 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 specified in the Code.
% N: returns a carriage return line break, which is \ r \ n on Windows and \ n on Unix ".
% X: NDC associated with the current thread (nested Diagnostic Environment), especially used in applications with multiple clients and multithreading such as java servlets.
%: Output A "%" character.
Additionally, you can add modifiers between % and formatted characters to control the minimum length, maximum length, and text alignment. For example:
1) c: specify the name of the output category. The minimum length is 20. If the length of the category name is smaller than 20, the right alignment is used by default.
2) %-20c: "-" indicates left alignment.
3) %. 30c: specify the name of the output category. The maximum length is 30. If the length of the category name is greater than 30, the extra characters on the left are truncated, if it is less than 30, no space will be filled.

Appendix: Comprehensive Log4j Configuration

The Log4j configuration file provides a full set of functions such as output to the console, files, rollback files, sending log emails, output to database log tables, and custom tags.
Log4j. rootLogger = DEBUG, console, dailyFile, im
Log4j.additivity.org. apache = true
# Console)
Log4j. appender. console = org. apache. log4j. leleappender
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 = [%-5 p] % d (% r) --> [% t] % l: % m % x % n

# 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 = [%-5 p] % d (% r) --> [% t] % l: % m % x % n
# 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 = [%-5 p] % d (% r) --> [% t] % l: % m % x % n
# Regularly roll back log files (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 = [%-5 p] % d (% r) --> [% t] % l: % m % x % n
# Apply 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 = [%-5 p] % 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 Logs to a specified email
Log4j. appender. mail = org.apache.log4j.net. SMTPAppender
Log4j. appender. mail. Threshold = FATAL
Log4j. appender. mail. BufferSize = 10
Log4j. appender. mail. From = xxx@mail.com
Log4j. appender. mail. SMTPHost = mail.com
Log4j. appender. mail. Subject = Log4J Message
Log4j. appender. mail. To = xxx@mail.com
Log4j. appender. mail. layout = org. apache. log4j. PatternLayout
Log4j. appender. mail. layout. ConversionPattern = [%-5 p] % d (% r) --> [% t] % l: % m % x % n
# Apply to databases
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 ('= [%-5 p] % d (% r) --> [% t] % l: % m % x % n ')
Log4j. appender. database. layout = org. apache. log4j. PatternLayout
Log4j. appender. database. layout. ConversionPattern = [%-5 p] % 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 = corlin@cybercorlin.net
Log4j. appender. im. layout = org. apache. log4j. PatternLayout
Log4j. appender. im. layout. ConversionPattern = [%-5 p] % d (% r) --> [% t] % l: % m % x % n


There is no doubt about the powerful functions of log4j, but in actual applications, it is inevitable that an independent log file needs to be output for a function. How can we separate the required content from the original log, what about creating a separate log file? In fact, you can easily implement this function with a slight configuration based on the existing log4j.

First look at a common log4j. properties file, which records logs in the console and myweb. log file:

Log4j. rootLogger = DEBUG, stdout, logfile
Log4j.category.org. springframework = ERROR
Log4j.category.org. apache = INFO


Log4j. appender. stdout = org. apache. log4j. leleappender
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 (using cn.com. Test as an example), you must first define in Test. java:

Private static Log logger = LogFactory. getLog (Test. class );

Then add the following to 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 logger in cn.com. Test use the configuration made by log4j. appender. test.

However, what if multiple log files need to be output in the same category? In fact, the truth is the same. First, we define it in Test. java:

Private static Log logger1 = LogFactory. getLog ("myTest1 ");
Private static Log logger2 = LogFactory. getLog ("myTest2 ");

Then add the following to 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 logger is used, give it a custom name (for example, "myTest1"), and then configure it in log4j. properties. Do not forget to use different logger for different logs (for example, logger1.info ("abc") for output to test1.log ")).
Another problem is that these custom logs are output to the logs configured by log4j. rootLogger at the same time by default. How can they only be output to the specified logs? Don't worry. Here is a switch:

Log4j. additi.pdf. myTest1 = false

It is used to set whether to output data to the log configured by log4j. rootLogger at the same time. If it is set to false, it will not be output to other places! Note that "myTest1" here is the custom name you gave logger in the program!

If you say that I just don't want to output this log to the logfile configured by log4j. rootLogger at the same time, I still want to output this log in stdout! Let's do it. Change your log4j. logger. myTest1 = DEBUG and test1 to the next step!
Log4j. logger. myTest1 = DEBUG, test1

 

// A configuration item in the actual project is attached below

Log4j. rootLogger = INFO, stdout, scribe

# Stdout type
Log4j. appender. stdout = org. apache. log4j. leleappender
Log4j. appender. stdout. layout = org. apache. log4j. PatternLayout
Log4j. appender. stdout. layout. ConversionPattern = [ip2city-finagle] [% t] % d {yyyy MM dd HH: mm: ss, SSS} [% p] % m % n

 

# Fileout
Log4j. appender. file = org. apache. log4j. RollingFileAppender
Log4j. appender. file. File =/data/online/ganji_services/logs/ip2city/ip2city. log
Log4j. appender. file. Append = true
Log4j. appender. file. Threshold = INFO
Log4j. appender. file. MaxFileSize = 150 MB
Log4j. appender. file. MaxBackupIndex = 10
Log4j. appender. file. layout = org. apache. log4j. PatternLayout
Log4j. appender. file. layout. ConversionPattern = [ip2city-finagle] [% t] % d {yyyy MM dd HH: mm: ss, SSS} [% p] % m % n


Log4j. appender. scribe = org. apache. log4j. scribe. ScribeAppender
Log4j. appender. scribe. Threshold = WARN
Log4j. appender. scribe. scribe_host = 127.0.0.1
Log4j. appender. scribe. scribe_port = 11463
Log4j. appender. scribe. scribe_category = common_service.ip2city-finagle
Log4j. appender. scribe. layout = org. apache. log4j. PatternLayout
Log4j. appender. scribe. layout. ConversionPattern = % d {yyyy/MM/dd HH: mm: ss} [% p] % F (line % L) % m

#
Log4j. appender. http_access = org. apache. log4j. RollingFileAppender # specifies the class to implement.
Log4j. appender. http_access.File =/data/online/ganji_services/logs/ip2city/ip2city_http_access1.log
Log4j. appender. http_access.Append = true
Log4j. appender. http_access.Threshold = INFO
Log4j. appender. http_access.MaxFileSize = 150 MB
Log4j. appender. http_access.MaxBackupIndex = 10
Log4j. appender. http_access.layout = org. apache. log4j. PatternLayout
Log4j. appender. http_access.layout.ConversionPattern = [ip2city-finagle] [% t] % d {yyyy MM dd HH: mm: ss, SSS} [% p] % m % n

Log4j. appender. thrift_access = org. apache. log4j. RollingFileAppender
Log4j. appender. thrift_access.File =/data/online/ganji_services/logs/ip2city/ip2city_thrift_access.log
Log4j. appender. thrift_access.Append = true
Log4j. appender. thrift_access.Threshold = INFO
Log4j. appender. thrift_access.MaxFileSize = 150 MB
Log4j. appender. thrift_access.MaxBackupIndex = 10
Log4j. appender. thrift_access.layout = org. apache. log4j. PatternLayout
Log4j. appender. thrift_access.layout.ConversionPattern = [ip2city-finagle] [% t] % d {yyyy MM dd HH: mm: ss, SSS} [% p] % m % n

Log4j. appender. hotIpCountLog = org. apache. log4j. DailyRollingFileAppender
Log4j. appender. hotIpCountLog. File =/data/online/ganji_services/logs/ip2city/hotIpCount. log
Log4j. appender. hotIpCountLog. Append = true
Log4j. appender. hotIpCountLog. Threshold = INFO
Log4j. appender. hotIpCountLog. DatePattern = '. 'yyyy-MM-dd
# Log4j. appender. hotIpCountLog. MaxFileSize = 150 MB
# Log4j. appender. hotIpCountLog. MaxBackupIndex = 10
Log4j. appender. hotIpCountLog. layout = org. apache. log4j. PatternLayout
# Log4j. appender. hotIpCountLog. layout. ConversionPattern = [% t] % d {yyyy MM dd} [% p] % m % n

Log4j.logger.com. ganji = INFO, file, scribe
Log4j.logger.com. ganji. arch. ip2city. finagleservice. logs. HttpAccessLog = INFO, http_access
Log4j.additivity.com. ganji. arch. ip2city. finagleservice. logs. HttpAccessLog = false
Log4j.logger.com. ganji. arch. ip2city. finagleservice. logs. ThriftAccessLog = INFO, thrift_access
Log4j.additivity.com. ganji. arch. ip2city. finagleservice. logs. ThriftAccessLog = false
Log4j.logger.com. ganji. arch. ip2city. finagleservice. logs. HotIpCountLog = INFO, hotIpCountLog
Log4j.additivity.com. ganji. arch. ip2city. finagleservice. logs. HotIpCountLog = false

 

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.