springBoot integration log4j

What are log4j and log4j2

  • Log4j: an open source project of Apache, which can control the destination of log information transmission to console, files, GUI components, etc., and control the output format of each log. These can be flexibly configured through a configuration file without modifying the application code. Although the maintenance has been stopped, most enterprises use log4j.
  • Log4j2: log4j2 is not just an upgraded version of log4j. It has been rewritten from beginning to end

Why log4j2

Compared with other log systems, log4j2 loses less data; Under the multithreading environment, the performance of the disruptor technology is more than 10 times higher than that of logback; Using jdk1 5. Concurrency, which reduces the occurrence of deadlock;  

Dependency introduction

pom pay special attention to spring-boot The log is added by default in the dependency of. log4j2 cannot take effect until it is removed. Otherwise, the package conflicts.

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-web</artifactId>  
    <exclusions><!-- Remove springboot Default configuration -->  
        <exclusion>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-logging</artifactId>  
        </exclusion>  
    </exclusions>  
</dependency> 

<dependency> <!-- introduce log4j2 rely on -->  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-log4j2</artifactId>  
</dependency> 

configuration file

The configuration file of log4j2 defaults to log4j2 spring XML. If it is not renamed, the configuration file path in the value yml may not be used

logging:
  config: xxxx.xml
  level:
    cn.jay.repository: trace

Profile template

Log4j is through a The properties file is used as the main configuration file, but log4j2 has abandoned this method and adopts xml,. json or jsn does this in this way, which may also be an inevitability of technology development, because the readability of the properties file is really a little poor.

<?xml version="1.0" encoding="UTF-8"?>
<!--Configuration hinder status,This is used to set log4j2 The internal information output can not be set when it is set to trace You'll see log4j2 Various internal detailed outputs-->
<!--monitorInterval: Log4j It can automatically detect and modify the configuration file and reconfigure itself, and set the interval seconds-->
<configuration monitorInterval="5">
  <!--Log level and prioritization: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->

  <!--Variable configuration-->
  <Properties>
    <!-- Format output:%date Indicates the date,%thread Represents the thread name,%-5level: The level is displayed 5 characters wide from the left %msg: Log messages,%n Is a newline character-->
    <!-- %logger{36} express Logger The maximum length of the first name is 36 characters -->
    <property name="LOG_PATTERN" value="%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" />
    <!-- Define the path to the log store -->
    <property name="FILE_PATH" value="Change to your log path" />
    <property name="FILE_NAME" value="Replace with your project name" />
  </Properties>

  <appenders>

    <console name="Console" target="SYSTEM_OUT">
      <!--Format of output log-->
      <PatternLayout pattern="${LOG_PATTERN}"/>
      <!--Console output only level And above( onMatch),Other direct rejection( onMismatch)-->
      <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
    </console>

    <!--The file will print out all the information, this log The program will be emptied automatically every time it runs, and the append Attribute, suitable for temporary testing-->
    <File name="Filelog" fileName="${FILE_PATH}/test.log" append="false">
      <PatternLayout pattern="${LOG_PATTERN}"/>
    </File>

    <!-- This will print out all the information info And below, each time the size exceeds size,Then this size Logs of size are automatically saved by year-The folder created in the month is compressed as an archive-->
    <RollingFile name="RollingFileInfo" fileName="${FILE_PATH}/info.log" filePattern="${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz">
      <!--Console output only level And above( onMatch),Other direct rejection( onMismatch)-->
      <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
      <PatternLayout pattern="${LOG_PATTERN}"/>
      <Policies>
        <!--interval Property is used to specify how often to scroll. The default is 1 hour-->
        <TimeBasedTriggeringPolicy interval="1"/>
        <SizeBasedTriggeringPolicy size="10MB"/>
      </Policies>
      <!-- DefaultRolloverStrategy If the property is not set, the default is to start overwriting up to 7 files in the same folder-->
      <DefaultRolloverStrategy max="15"/>
    </RollingFile>

    <!-- This will print out all the information warn And below, each time the size exceeds size,Then this size Logs of size are automatically saved by year-The folder created in the month is compressed as an archive-->
    <RollingFile name="RollingFileWarn" fileName="${FILE_PATH}/warn.log" filePattern="${FILE_PATH}/${FILE_NAME}-WARN-%d{yyyy-MM-dd}_%i.log.gz">
      <!--Console output only level And above( onMatch),Other direct rejection( onMismatch)-->
      <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
      <PatternLayout pattern="${LOG_PATTERN}"/>
      <Policies>
        <!--interval Property is used to specify how often to scroll. The default is 1 hour-->
        <TimeBasedTriggeringPolicy interval="1"/>
        <SizeBasedTriggeringPolicy size="10MB"/>
      </Policies>
      <!-- DefaultRolloverStrategy If the property is not set, the default is to start overwriting up to 7 files in the same folder-->
      <DefaultRolloverStrategy max="15"/>
    </RollingFile>

    <!-- This will print out all the information error And below, each time the size exceeds size,Then this size Logs of size are automatically saved by year-The folder created in the month is compressed as an archive-->
    <RollingFile name="RollingFileError" fileName="${FILE_PATH}/error.log" filePattern="${FILE_PATH}/${FILE_NAME}-ERROR-%d{yyyy-MM-dd}_%i.log.gz">
      <!--Console output only level And above( onMatch),Other direct rejection( onMismatch)-->
      <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
      <PatternLayout pattern="${LOG_PATTERN}"/>
      <Policies>
        <!--interval Property is used to specify how often to scroll. The default is 1 hour-->
        <TimeBasedTriggeringPolicy interval="1"/>
        <SizeBasedTriggeringPolicy size="10MB"/>
      </Policies>
      <!-- DefaultRolloverStrategy If the property is not set, the default is to start overwriting up to 7 files in the same folder-->
      <DefaultRolloverStrategy max="15"/>
    </RollingFile>

  </appenders>

  <!--Logger The node is used to specify the log format separately, for example, for the log under the specified package class Specify different log levels, etc.-->
  <!--Then define loggers,Only defined logger And introduced appender,appender Will take effect-->
  <loggers>

    <!--Filter out spring and mybatis Some useless DEBUG information-->
    <logger name="org.mybatis" level="info" additivity="false">
      <AppenderRef ref="Console"/>
    </logger>
    <!--Monitoring system information-->
    <!--If additivity Set as false,Zezi Logger Only in their own appender Output in, not in the parent Logger of appender Output in.-->
    <Logger name="org.springframework" level="info" additivity="false">
      <AppenderRef ref="Console"/>
    </Logger>

    <root level="info">
      <appender-ref ref="Console"/>
      <appender-ref ref="Filelog"/>
      <appender-ref ref="RollingFileInfo"/>
      <appender-ref ref="RollingFileWarn"/>
      <appender-ref ref="RollingFileError"/>
    </root>
  </loggers>

</configuration>

Introduction to configuration parameters

log level

  • Trace: trace means that the program advances and can write trace output
  • debug: debugging. Generally, it is the lowest level, and trace is basically not used.
  • info: output important information and use it more
  • warn: warning, some messages are not error messages, but you should also give some hints to the programmer.
  • Error: error message. Also used a lot.
  • Fatal: fatal error.

Output source

  • CONSOLE (output to CONSOLE)
  • FILE (output to FILE)

Format

  • SimpleLayout: displays in a simple form
  • HTMLLayout: display in HTML table
  • PatternLayout: custom form display

Custom layout

%d{yyyy-MM-dd HH:mm:ss, SSS} : Log production time,Time to output in milliseconds
%-5level : Output log level,-5 Indicates left alignment and fixed output of 5 characters. If it is insufficient, fill 0 on the right
%c : logger Name of(%logger)
%t : Output current thread name
%p : Log output format
%m : Log content, i.e logger.info("message")
%n : Newline character
%C : Java Class name(%F)
%L : Line number
%M : Method name
%l : The number of lines in which the output statement is located, Including class name, method name, file name and number of lines
hostName : Local machine name
hostAddress : local ip address

reference resources

https://www.cnblogs.com/keeya/p/10101547.html

Keywords: Java Spring Boot

Added by leegreaves on Sun, 26 Dec 2021 20:42:44 +0200