The configuration file for log4j is parsed in detail

  • 2020-04-01 02:11:50
  • OfStack

1. The advantages of Log4j
Log4j is an open source project of Apache. By using Log4j, we can control where log information is sent. We can also control the output format of each log; By defining the level of each log message, 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 changing the application code.

The benefits of log4j are:
(1) by modifying the configuration file, you can determine the destination of the log information -- the console, the files, the GUI components, even the sleeve interface server, the NT event logger, the UNIX Syslog daemon, and so on.

(2) by modifying the configuration file, the level of each log information can be defined to control whether or not to output. Detailed log information can be printed in the System development phase to track the System's performance, and log output can be turned off after the System is stable, so as to track the System's performance while reducing the garbage code (system.out.println (...)). , etc.).

(3) with log4j, the whole system needs to have a unified log mechanism, which is conducive to the planning of the system.

2. Configuration files
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 FATAL, ERROR, WARN, INFO, DEBUG, TRACE and ALL, which are used 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 to a file; The output format controls the display of log information.

2.1 priority of log information
Log4j recommends using only four levels, with the highest to lowest priority being ERROR, WARN, INFO, and DEBUG. With the level defined here, you can control the switch to log information at the appropriate level in the application. If the INFO level is defined here, all log information in the application below the INFO level will not be printed.

2.2 use of output source
Selective use or disabling of log requests is only part of Log4j's functionality. Log4j allows log requests to be output to multiple output sources. In Log4j parlance, an output source is called an Appender.

Appenders include console, files, GUI components, remote socket servers, JMS, NT Event Loggers, remote UNIX Syslog daemons. It can also do asynchronous logging. A logger can set more than one appender. Add an appender to a given logger with the addAppender method. For a given logger, each valid log request is forwarded to all appenders of the logger and to the appenders of the logger's parent logger.

2.2.1 ConsoleAppender
If you use a ConsoleAppender, the log information is written to the Console. The effect is equivalent to printing the information directly onto system.out.

2.2.2 FileAppender
With a FileAppender, the log information is written to the specified file. This should be the case more often. Accordingly, the filename of the log output should be specified in the configuration file. The following configuration specifies the log file name of log.txt.

Log4j. Appender. Appendername. The File = log. TXT to appendername replaced with specific configuration appender alias.

Note: the specified log file path problem

2.2.3 DailyRollingAppender
Using a FileAppender can output log information to a file, but it is not convenient to read if the file is too large. You can now use the DailyRollingAppender. The DailyRollingAppender can output Log information to files that are sorted by date. The configuration file will generate a log file every day (the time can be set), each log file only records the log information of the day:


log4j.appender.appendername=org.apache.log4j.DailyRollingFileAppender  
log4j.appender.Aappendername.file=log  
log4j.appender.appendername.DatePattern='.'yyyy-MM-dd  
log4j.appender.appendername.layout=org.apache.log4j.PatternLayout  
log4j.appender.appendername.layout.ConversionPattern= %5r %-5p %c{2} - %m%n 

2.2.4 RollingFileAppender
A new file is created when the file size reaches the specified size.

og4j.appender.appendername=org.apache.log4j.RollingFileAppender  
log4j.appender.appendername.File= ../logs/rlog.log  
# Control the maximum log file size  
log4j.appender.appendername.MaxFileSize=100KB  
# Archive log files (one backup file here)  
log4j.appender.appendername.MaxBackupIndex=1
log4j.appender.appendername.layout=org.apache.log4j.PatternLayout  
log4j.appender.appendername.layout.ConversionPattern=%p %t %c - %m%n 

This configuration file specifies the output source appendername, which is a round-robin log file. The largest file is 100KB, and when a log file reaches its maximum size, Log4J automatically renuminates log.log to log.log.1, and then rebuilds a new log.log file, in turn.

2.2.5 WriterAppender
Sends log information in stream format to any specified location.

2.3 Layout configuration
Layout specifies the style of the log output.

2.3.1 layout style


org.apache.log4j.HTMLLayout (in HTML Tabular layout),   
org.apache.log4j.PatternLayout (you can specify layout patterns flexibly),   
org.apache.log4j.SimpleLayout (the level and information string containing the log information),   
org.apache.log4j.TTCCLayout (contains information about when the log was generated, the thread, the category, and so on)   

2.3.2 format

%m  Output the message specified in the code   
%p  Output priority, i.e DEBUG . INFO . WARN . ERROR . FATAL  
%r  Output from application startup to output the log The number of milliseconds the information takes   
%c  The class to which the output belongs is usually the full name of the class   
%t  Output the name of the thread that produced the log event   
%n  Output a line return, Windows Platform for "rn" . Unix Platform for "n"  
%d  Output the date or time of the log time point in the default format of ISO8601 , you can also specify the format later, for example: %d{yyy MMM dd HH:mm:ss,SSS} , the output is similar to: 2002 years 10 month 18 day  22 : 10 : 28 . 921  
%l  Output the location where the log event occurred, including the class name, the thread that occurred, and the number of lines in the code. For example: Testlog4.main(Test Log4.java:10) 

3. Set log output levels for different appenders
This can be done by modifying the Appender Threshold in the configuration, as in the following example:

Profile:
Log4j rootLogger = debug, A, B, C

Output to the console
Log4j. Appender. A = org, apache log4j. ConsoleAppender
Log4j. Appender. A.T arget = System. Out
Log4j. Appender. A. ayout = org.. Apache log4j. PatternLayout
Log4j. Appender. A. ayout. ConversionPattern = % p % t % c - % m % n

Output to log files
Log4j. Appender. B = org. Apache. Log4j. DailyRollingFileAppender
Log4j. Appender. B. ile = logs/log. The log
Log4j. Appender. B.A ppend = true
Log4j. Appender. B.T hreshold = # DEBUG output EBUG level over the log
Log4j. Appender. B.l ayout = org.. Apache log4j. PatternLayout
Log4j. Appender. B.l ayout. ConversionPattern = % p % t % c - % m % n

Save the exception information to a separate file
Log4j. Appender. C = org. Apache. Log4j. DailyRollingFileAppender
Log4j.appender.c.file = logs/error.log # exception log file name
Log4j. Appender. C.a. ppend = true
Log4j. Appender. C.T hreshold = ERROR # only output ERROR level over the log
Log4j. Appender. C.l ayout = org.. Apache log4j. PatternLayout
Log4j. Appender. C.l ayout. ConversionPattern = % p % t % c - % m % n

Example:


public class TestLog4j
{
    public static void main(String[] args)
    {
        PropertyConfigurator.configure("D:/Code/conf/log4j.properties");
        Logger logger = Logger.getLogger(TestLog4j.class);
        logger.debug("debug");
        logger.error("error");   
    }
}


Related articles: