Log4j2 configuration and use

Log4j2: A log management tool. The upgraded version of Log4j requires Java6 or above
 
1. Install the log4j2 dependency package
1. Directly import jar through maven's pom.xml:
log4j-api和log4j-core
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.0</version>
</dependency>

 

2. Download the jar package from the official website and directly import it into the project
 
Second, the configuration file of log4j2
 
1. Configuration file location and naming rules
The following is the content of the official website. Find files in the order of 1-8, and use [log4j.configurationFile] first.
  1. Log4j will inspect the "log4j.configurationFile" system property and, if set, will attempt to load the configuration using the ConfigurationFactory that matches the file extension.
  2. If no system property is set the YAML ConfigurationFactory will look for log4j2-test.yaml or log4j2-test.yml in the classpath.
  3. If no such file is found the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.
  4. If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
  5. If a test file cannot be located the YAML ConfigurationFactory will look for log4j2.yaml or log4j2.yml on the classpath.
  6. If a YAML file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.
  7. If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.
  8. If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.
 
2. Detailed configuration
The configuration method of XML format file is listed below, and it can also be configured in Json format. It is introduced on the official website: http://logging.apache.org/log4j/log4j-2.3/manual/configuration.html
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ERROR">
  <!--Configuration 配置项
  status: log level of log4j itself, "trace", "debug", "info", "warn", "error" and "fatal"
  monitorInterval: How many seconds to re-read the configuration file, you can modify the configuration without restarting --> 
  < Appenders > 
    <!-- Appenders define log output, including Console, File, RollingRandomAccessFile, MongoDB, Flume, etc.
    There is Console: output source to console
    File: Output the log to a file, specify the file to store to by fileName (the directory will be automatically created if it does not exist)
    RollingRandomAccessFile: It is also written to a file, but rules can be defined to recreate a new log file storage according to file size or time; if it is divided by time, it needs to be used with filePattern
    -->
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %F %logger{36} - %msg%n"/>
      <!--PatternLayout指定输出日志的格式 -->
    </Console>
    <File name="debuglog" fileName="./log/debug.log" append="true">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
    </File>
  </Appenders>
  <Loggers > 
    <!-- Logger, which logger to use is determined by the logger name of LogManager.getLogger(logger name)
    Divided into root root logger and custom logger --> 
    < Root level ="ERROR" > 
      <!-- When the corresponding logger cannot be found according to the name, the Root logger is used
      leve: log output level (default ERROR); TRACE > DEBUG > INFO > WARN > ERROR, ALL or OFF --> 
      < AppenderRef ref ="Console" /> 
      <!-- AppenderRef: Associate the output rules defined in Appenders, you can There are multiple, logs can be output to multiple places at the same time --> 
      < AppenderRef ref ="debuglog" /> 
    </ Root > 
    < Logger name ="customlog" level ="INFO" additivity ="false" > 
      <!-- Logger custom logger:
        name is the name of the logger, and the logger connection is obtained through LogManager.getLogger(logger name)
        additivity: Additivity. The default is true, if it is true, the current log content will also be printed to the logger above it, where the above logger is Root --> 
      < AppenderRef ref ="Console" /> 
    </ Logger > 
  </ Loggers > 
</ Configuration >
 

 

 
More log output formats (PatternLayout)

%d{HH:mm:ss.SSS} means the time to output to milliseconds
%t output the current thread name
%-5level output log level, -5 means left-aligned and fixed output of 5 characters, if not enough, add 0 to the right
%logger Output logger name, because Root Logger has no name, so no output
%msg log text
%n newline

Other commonly used placeholders are:
%F The name of the class file where the output is located, such as Log4j2Test.java
%L The output line number
%M The method name where the output is located
%l The number of lines where the output statement is located, including the class name, method name, file name ,Rows

 
 
More configuration items for RollingRandomAccessFile

fileName specifies the location and file name of the current log file
filePattern specifies the file transfer and renaming rules when Rolling occurs
SizeBasedTriggeringPolicy specifies that when the file size is larger than the value specified by size, the Rolling is triggered
DefaultRolloverStrategy specifies the maximum number of files to save
TimeBasedTriggeringPolicy This configuration requires Used in combination with filePattern, note that the file renaming rule configured in filePattern is ${FILE_NAME}-%d{yyyy-MM-dd HH-mm}-%i, and the minimum time granularity is mm, that is,
the size specified by TimeBasedTriggeringPolicy in minutes is 1, the combination is to generate a new file every 1 minute. If it is changed to %d{yyyy-MM-dd HH}, the minimum granularity is hour, and a file is generated every hour

3. Java
package util;
 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
 
public class Log {
 
    static  final Logger logger_root = LogManager.getLogger( Log.class .getName()); // The configuration file does not configure the class name of Log, so use the default Root 
    static  final Logger logger_custom = LogManager.getLogger("customlog"); // The configuration file defines customlog, so use customlog
 
    public  static  void main(String[] args) {
         // Record debug level information 
        logger_root.debug("This is debug message." );
         // Record info level information 
        logger_root.info("This is info message." ) ;
         // Record error level information 
        logger_root.error("This is error message." );
 
        // Record debug level information 
        logger_custom.debug("This is debug message." );
         // Record info level information 
        logger_custom.info("This is info message." );
         // Record error level information 
        logger_custom.error ("This is error message." );
    }
}

 

illustrate:
LogManager.getLogger(Log name): Get a Logger object
Output logs (trace, debug, info, warn, error, fatal) through .debug of the Logger object
 
Results of the:
15:23:53.087 [main] ERROR Log.java util.Log - This is error message.
15:23:53.096 [main] INFO  Log.java customlog - This is info message.
15:23:53.097 [main] ERROR Log.java customlog - This is error message.
 
The log file output of hitting Root is as follows:
15:33:27.947 ERROR util.Log 17 main - This is error message.
 
 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325238013&siteId=291194637