Details of log4j log level configuration in Java

  • 2020-12-16 05:57:45
  • OfStack

1.1 introduction

It is a shame to say so. Recently, I was sent to the client company to interview for the outsourcing development position. I had prepared some interview questions related to redis, rabbitMQ and SSM frameworks and reviewed one project I had done. How are log levels configured? At that time, I was even covered by X, which was usually provided by the project manager. I also randomly searched for OK on the Internet and pasted it on the configuration file 1. After I said that, the interviewer gave me a deep stare, and I felt so ashamed inside...

1.2 Without further ado, let's talk about the development story of the log (if you already know, you can skip to the 1.3 log configuration).

For more insight into logging implementations, I personally recommend logback + slf4j. As for the log configuration, it is a good idea to know log4j, as most of the current projects still use log4j. Well, here's the story:

In 1999, the Apache open source community released log4j, which caused a stir in the programming world and has since become the standard for logging and widely used by java programmers. Sun subsequently released the Logging mechanism (ES28en.util.logging, JUL) in version 1.4 of JDK, but the mechanism was not recognized by the public, which is a pity. Soon Apache was launched commons - logging logging framework (allows developers to abstract the logging implementation way which logging technology, rather than having to focus on the specific use in popular culture is what you want to use mobile phone call, if you are in Beijing, you will call to Beijing, you will call to Hong Kong in Hong Kong, drops), the framework was for Sun vile wind, it can automatically find the call log output logging technology to the current environment, the logging framework can support log4j or JUL. commons-logging +log4j became the classic combination of Java logs for a long time after that. However, commons-ES45en has not been updated for a period of time. I wonder if the original design of ES46en-ES47en is not good enough and it is more difficult to optimize it again. Why do you say so? This author (Ceki ES51enlcu) is one of the authors of log4j. His slf4j is more elegant in design, and he also implements logback technology, which is more advanced than log4j. At this point, the dominant position of the logging system from ES60en-logging +log4j1 began to be shaken, and various ES64en-ES65en +log4j? slf4j + log4j? slf4j + logback? Match, really let a person worry. To make matters worse, Ceki ES76enES77enu boss helped to optimize log4j, and the world now has another logging technology --log4j2. This is to learn to engage in Tencent WeChat and QQ, it is 666. So if you want to know more about logging technology, you can look for information on logback + slf4j. As for the configuration file, I think you should understand the log4j configuration details I wrote below. After all, many companies still use the log4j framework.

1.3 To get down to business, log4j log basic configuration

1. Create a new ES99en4j.properties file under classpath or resource package (maven project) of the project. The following parameters are sufficient for the initial project configuration

1.4log4j log level configuration;


# Specify the log level and output source with the root logger  
# Priority of log output:  debug < info < warn < error < fatal
# Determine the log level of the Yigen logger (info) And the alias name of the output source (console,myFile)
# This definition allows logs to be output in the console and file, and only output info Log above level 
log4j.rootLogger=info,console,myFile
####### Configure the output source console The concrete implementation of console output #######
# Define the output source alias console (That is, the output source defined by the root logger) 
# The implementation class of ConsoleAppender (Console output source) log4j.appender.console=org.apache.log4j.ConsoleAppender 
# The format converter that specifies the log output format is PatternLayout The implementation class 
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# Define the specific format of the log output 
log4j.appender.console.layout.ConversionPattern=%d %-5p [%c.%M()] - %m%n 
####### Configure the output source myFile The concrete implementation of the file output #######
# Define the output source alias myFile (That is, the output source defined by the root logger) 
# The implementation class of RollingFileAppender (File output source) log4j.appender.myFile=org.apache.log4j.RollingFileAppender
# Defines the storage path for log files 
log4j.appender.myFile.File=src/log/logProperties/log4j.log
# Defines the size of the log file 
log4j.appender.myFile.MaxFileSize=1024kb
# Define log files to generate up to a few (from 0 Begin to calculate 1 That's the most here 3 A file) 
# Exceeding this size overwrites the previously generated file 
log4j.appender.myFile.MaxBackupIndex=2
# The format converter that specifies the log output format is PatternLayout The implementation class 
log4j.appender.myFile.layout=org.apache.log4j.PatternLayout
# Define the specific format of the log output 
log4j.appender.console.layout.ConversionPattern=%d %-5p [%c.%M()] - %m%n 
####### Output format interpretation #######
#%d:  The point at which the log is printed, the default format is ISO8601 , you can also specify a different format, 
   # The definition is as follows:  %d{yyy years MM month dd day  HH when mm points ss seconds SSS} , it will output: 
   #2018 years 01 month 06 day  14 when 47 points 45 seconds 590
#%p:  Output the log level, i.e DEBUG . INFO . WARN . ERROR . FATAL
   #%-5p : Indicates the character is less than 5 , the character is placed to the left (without" - "Is to the right of the character), you can raise 1 the 3
#%c:  The full name of the class in which the log resides 
#%M:  The name of the method where the log is located 
#%m:  Log information 
#%n:  The output 1 A carriage return line break 
#%L:  The line number in the output code 

2. Invoke log test configuration results.


import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class LogPropertiesTest {
 public static void main(String[] args) {
  /* Parsing the classpath Under the configuration file 
  String log4jPath=System.getProperty("user.dir")+"\\src\\log\\logProperties\\log4j.properties";
  PropertyConfigurator.configure(log4jPath);*/
  Logger log = LogManager.getLogger(LogPropertiesTest.class);
  log.debug(" debugging ");
  log.info(" information ");
  log.warn(" warning ");
  log.error(" error ");
  log.fatal(" A fatal error ");
 }
}

1.4 Log level configuration

The log level configuration can be divided into three categories, such as the above configuration is the log level of the configuration parent logger, the second is the log level of the configuration subclass logger, and the third is the log level of the configuration output source (console, file, and so on). Their log level resolution is ranked from low to high priority. Forgive me for not being clear, just be direct
On case, everybody should be able to understand!

1. If the log level of the parent logger (rootLogger) is configured (and must be configured), and the log level of the subclass logger is not configured, and the log level of the output source is not configured, the output source can only output the log level above the INFO level;

2. If the log level of the parent logger (rootLogger) is configured (assuming INFO) and the log level of the subclass logger (assuming DEBUG) is configured, and the log level of the output source is not configured, then the output source outputs the log level above DEBUG;

3. If the log level of the parent logger (rootLogger) is configured (assuming INFO level), the log level of the subclass logger is configured (assuming DEBUG level), and the log level of the output source is configured (assuming INFO level), then the output source outputs above INFO level;

4. If the log level of the parent logger (INFO) is configured (and must be configured), the log level of the subclass logger is not configured, the configuration

Is the log level of the output source (assuming DEBUG level), then the output source outputs the log level above INFO level;

Therefore, we know from the above case that there are two logical relationships between the logger and the output source output log level:

1. If the output source does not define the logging level, it inherits the logging level of its closest subclass logger; The subclass logger does not define the logging level and inherits the parent class logger that is closest to it.

2. When printing logs, the output source will compare the log level defined by itself to that of the nearest subclass logger. If the output source defines a level higher than the subclass logger, the output will be at the log level defined by the output source, and vice versa.

Therefore, log levels can be configured in a daily configuration mode in the project:


# The logging level of the control parent logger is info , the default output under all modules only info Log above level 
log4j.rootLogger=info,console
# The log level under a single control module is error, The log is only printed when an exception occurs 
log4j.logger.log.logProperties=error
# Control the logging level of a class individually debug, Easy to output debugging information 
log4j.logger.log.logProperties.LogPropertiesTest=debug
#############  Log output to the console  ############# 
# Log output to the console used by api class  
log4j.appender.console=org.apache.log4j.ConsoleAppender 
# Specify the log level of the current output source. With the previous configuration, you do not need to configure this item 
#log4j.appender.console.Threshold = info
# Specify the format of the log output: flexible format 
log4j.appender.console.layout=org.apache.log4j.PatternLayout 
# Specific format of the content 
log4j.appender.console.layout.ConversionPattern=%d %-2p [%c.%M()] - %m%n 

1.5 the conclusion

At this point, I believe you have a basic grasp of log configuration. There are many places in the text may be wrong, welcome to point out. I also wrote the summary in order to have a deep understanding of the configuration of the technology, so That I can have a deeper understanding of it.


Related articles: