1.Advantages of Log4j
Log4j is an open source project of Apache. By using Log4j, we can control the delivery location of log information; we can also control the output format of each log; by defining the level of each log information, we can control the log in more detail. generation process. The most interesting thing is that these can be flexibly configured through a configuration file without modifying the application code.
The benefits of log4j are:
(1) By modifying the configuration file, you can decide the destination of the log information-console, file, GUI component, even socket server, NT event recorder, UNIX Syslog daemon, etc.
(2) By modifying the configuration file, you can define the level of each log message to control whether it is output. During the system development stage, detailed log information can be printed to track the system operation. After the system is stable, the log output can be turned off, thereby tracking the system operation while reducing junk code (System.out.println(.. ....)wait).
(3) Using log4j requires a unified log mechanism for the entire system, which is conducive to system planning.
2. Configuration file
Log4j consists of three important components: the priority of log information, the output destination of log information, and the output format of log information. The priorities of log information from high to low include FATAL, ERROR, WARN, INFO, DEBUG, TRACE, and ALL, which are used to specify the importance of this log information respectively; the output destination of the log information specifies that the log will be printed to the console Or in the file; and the output format controls the display content of the log information.
2.1 Priority of log information
Log4j recommends using only four levels. The priorities from high to low are ERROR, WARN, INFO, and DEBUG. Through the levels defined here, you can control the on and off of the corresponding level of log information in the application. If the INFO level is defined here, all log information below the INFO level in the application will not be printed.
2.2 Use of output sources
Selectively enabling or disabling logging requests is only part of the functionality of Log4j. Log4j allows logging requests to be output to multiple output sources. In Log4j terms, an output source is called an Appender.
Appender includes console, files, GUI components, remote socket servers, JMS, NT Event Loggers, remote UNIX Syslog daemons (Remote UNIX background log service). It can also record asynchronously. A logger can set more than one appender. Add an appender to a given logger using the addAppender method. For a given logger, each valid log request is forwarded to all appenders of the logger and the appenders of the logger's parent logger.
2.2.1 ConsoleAppender
If ConsoleAppender is used, log information will be written to Console. The effect is equivalent to printing information directly to System.out.
2.2.2 FileAppender
Using FileAppender, the log information will be written to the specified file. This should be a more frequently used situation. Accordingly, the file name of the log output should be specified in the configuration file. The following configuration specifies the log file name log.txt.
log4j.appender.appendername.File=log.txt Note that appendername is replaced by the alias of Appender in the specific configuration.
Note: Problem with the specified log file path
2.2.3 DailyRollingAppender
You can use FileAppender to output log information to a file, but if the file is too large, it will be inconvenient to read. At this time you can use DailyRollingAppender. DailyRollingAppender can output Log information to files separated by date. The configuration file will generate a log file every day (the time can be set), and each log file only records the log information of that day:
Copy the code code as follows:
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 generated when the file size reaches the specified size.
Copy the code code as follows:
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 rotating log file. The largest file is 100KB. When a log file reaches the maximum size, Log4J will automatically rename rlog.log to rlog.log.1, then rebuild a new rlog.log file, and rotate in sequence.
2.2.5 WriterAppender
Send log information to any specified place in streaming format.
2.3 Layout configuration
Layout specifies the style of log information output.
2.3.1 Layout style
Copy the code code as follows:
org.apache.log4j.HTMLLayout (layout in HTML table format),
org.apache.log4j.PatternLayout (can flexibly specify layout patterns),
org.apache.log4j.SimpleLayout (contains the level and information string of the log information),
org.apache.log4j.TTCCLayout (contains log generation time, thread, category, etc. information)
2.3.2 Format
Copy the code code as follows:
%m outputs the message specified in the code
%p output priority, namely DEBUG, INFO, WARN, ERROR, FATAL
%r Outputs the number of milliseconds it took from application startup to outputting the log information.
%c outputs the category to which it belongs, usually the full name of the class.
%t outputs the name of the thread that generated the log event
%n outputs a carriage return and line feed character, which is "rn" on the Windows platform and "n" on the Unix platform.
%d outputs the date or time of the log time point. The default format is ISO8601. You can also specify the format afterwards, such as: %d{yyy MMM dd HH:mm:ss,SSS}. The output is similar to: October 18, 2002. 22:10:28,921
%l Outputs the location where the log event occurred, including the category name, the thread where it occurred, and the line number in the code. Example: Testlog4.main(Test Log4.java:10)
3.Set log output levels for different Appenders
This can be achieved by modifying the Appender's Threshold in the configuration, such as the following example:
Configuration file:
log4j.rootLogger = debug,A,B,C
#Output to console
log4j.appender.A = org.apache.log4j.ConsoleAppender
log4j.appender.A.Target = System.out
log4j.appender.A.layout = org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern = %p %t %c - %m%n
# Output to log file
log4j.appender.B = org.apache.log4j.DailyRollingFileAppender
log4j.appender.B.File = logs/log.log
log4j.appender.B.Append = true
log4j.appender.B.Threshold = DEBUG # Output logs above EBUG level
log4j.appender.B.layout = org.apache.log4j.PatternLayout
log4j.appender.B.layout.ConversionPattern = %p %t %c - %m%n
# Save 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.Append = true
log4j.appender.C.Threshold = ERROR #Only output logs above ERROR level
log4j.appender.C.layout = org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern = %p %t %c - %m%n
example:
Copy the code code as follows:
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");
}
}