Use Slf4j to integrate Log4j2 to build a project log system solution (not using Common-logging, Log4j)

1. The difference between Log4j, SLF4J, Common-logging

Both slf4j and commons-logging are specifications of the logging framework, and their implementation is very weak. Log4j is mainly aimed at the implementation of the former two logging frameworks. Slf4j has a tendency to replace commons-logging. Common-longing supports log4j by default. The following configuration is required to use other logging tools: common-logging.properties.

org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JCategoryLog

1.1 、 slf4j

slf4j (the full name is Simple Loging Facade For Java) is a unified interface that provides log output for Java programs. It is not a specific log implementation solution, just like the JDBC we often use, but just a rule. Therefore, slf4j alone cannot work. It must be combined with other specific log implementation solutions, such as org.apache.log4j.Logger of Apache, java.util.logging.Logger that comes with jdk and so on.
The corresponding jar package:
    slf4j-log4j12-xxxjar uses the driver provided by org.apache.log4j.Logger
    slf4j-jdk14-xxxjar uses the driver provided by java.util.logging
    slf4j-simple-xxxjar directly binds System.err
    slf4j -jcl-xxxjar is the driver provided by commons-logging
    logback-classic-xxxjar is the driver provided by logback

1.2, the difference between Log4j and Log4j2

log4j is an open source project of Apache, log4j2 and log4j are the authors, but log4j2 is a re-architected log component. He discarded the shortcomings of previous log4j and introduced a new component that absorbed the excellent logback design. . The log4j2 community is very active and updated quickly.

1. Configuration file type

Log4j uses a .properties file as the main configuration file, but the current log4j 2 has abandoned this method and uses .xml, .json or .jsn to do it.

2. Core JAR package

log4j only needs to introduce a jar package,

<dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.17</version>
</dependency>

And log4j 2 requires 2 cores

          <!-- slf4j核心包-->  
          <dependency>  
              <groupId>org.slf4j</groupId>  
              <artifactId>slf4j-api</artifactId>  
              <version>1.7.13</version>  
          </dependency>  
          <dependency>  
              <groupId>org.slf4j</groupId>  
              <artifactId>jcl-over-slf4j</artifactId>  
              <version>1.7.13</version>  
              <scope>runtime</scope>  
        </dependency>  

2. Use Slf4j to integrate Log4j2 to build a project log system

The log4j-based log system is reconstructed into a log system based on Slf4j and log4j2, because the use of slf4j can ensure that our log system has good compatibility and is compatible with several current common log systems. Using log4j2 instead of log4j is Because Log4j 1.x has a deadlock under high concurrency conditions, the cpu usage has soared abnormally, and Log4j2.0 based on LMAX Disruptor's asynchronous log performance in a multi-threaded environment will be far better than Log4j 1.x and logback (official data Is more than 10 times).

2.1 Construction steps

1. Dependency Management

1). Delete the log4j and slf4j-log4j12 dependencies required by Log4j1.x in the project.
2). Add the following slf4j and log4j2 dependencies.

<!--核心log4j2jar包-->
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-api</artifactId>
  <version>2.11.2</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.11.2</version>
</dependency>
<!--用于与slf4j保持桥接-->
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-slf4j-impl</artifactId>
  <version>2.11.2</version>
</dependency>
<!--web工程需要包含log4j-web,非web工程不需要-->
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-web</artifactId>
  <version>2.11.2</version>
</dependency>
<!--下面这个依赖与log4j-slf4j-impl只能二选一,一个是log4j2实现的一个是slf4j实现的-->
<!--
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
  <version>1.7.26</version>
</dependency>
-->
<!-- slf4j核心包-->
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>1.7.26</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>jcl-over-slf4j</artifactId>
  <version>1.7.26</version>
</dependency>

2. Set log4j2 listeners and filters in web.xml (this step is not required for servlet3.0 and above)

    <!--对于log4j2,Servlet2.5以前的版本需要-->  
    <listener>  
       <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>  
    </listener>  
    <filter>  
       <filter-name>log4jServletFilter</filter-name>  
       <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>  
    </filter>  
    <filter-mapping>  
      <filter-name>log4jServletFilter</filter-name>  
      <url-pattern>/*</url-pattern>  
      <dispatcher>REQUEST</dispatcher>  
      <dispatcher>FORWARD</dispatcher>  
      <dispatcher>INCLUDE</dispatcher>  
      <dispatcher>ERROR</dispatcher>  
   </filter-mapping>  

How to determine the Servlet version you are using?

1. Determine the servlet-api.jar in the lib folder of tomcat, open the MANIFEST.MF file in its META-INF folder with Notepad and see that the following code is the version number

Specification-Version: 3.1

The same is true for viewing the jsp version number, and the folder jsp-api.jar needs to be opened.

2. When using idea's Maven project, you need to add the following dependencies in the pom file

<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
</dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/jsp-api -->
<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
</dependency>

Among them, provided by scope means that you don't need to package it when packaging, and other facilities (Web Container) will provide it. In fact, the dependency can theoretically participate in the compiling, testing, and running cycles. Equivalent to compile, but the exclude action is done in the packaging stage.

3. Log4j2 no longer supports properties files. It only supports xml, json or yaml. If the location is not specified, it will search under src/main/resources by default.

If you need to customize the location, you need to add the following code in the above web.xml

<context-param>  
   <param-name>log4jConfiguration</param-name>  
   <param-value>/WEB-INF/classes/log4j2.xml</param-value>  
</context-param> 

4. Detailed explanation of log4j2.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!--status日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL-->
<Configuration status="off" monitorInterval="1800">
    <properties>
        <property name="LOG_HOME">/src/logs/</property>
        <property name="ERROR_LOG_FILE_NAME">error</property>
    </properties>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout  charset="GB18030" pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
        </Console>
        <RollingRandomAccessFile name="ErrorLog"
                                         fileName="${LOG_HOME}/${ERROR_LOG_FILE_NAME}.log"
                                         filePattern="${LOG_HOME}/${ERROR_LOG_FILE_NAME}.log.%d{yyyy-MM-dd}.gz">
            <PatternLayout charset="UTF-8"
                    pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="20 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="20"/>
        </RollingRandomAccessFile>
    </Appenders>
    <Loggers>
        <!-- 3rdparty Loggers -->
        <logger name="org.springframework.core" level="error"/>
        <logger name="org.springframework.beans" level="error"/>
        <logger name="org.springframework.context" level="error"/>
        <logger name="org.springframework.web" level="error"/>
        <Logger name="com.opensymphony.xwork2" level="error"/>
        <Logger name="org.apache.struts2" level="error"/>
        <logger name="com.hafiz.www.controller" level="error" includeLocation="true" additivity="false">
            <appender-ref ref="ErrorLog"/>
            <appender-ref ref="Console"/>
        </logger>
        <Root level="warn" includeLocation="true">
            <Appender-ref ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

The Appender that is configured with a RollingRandomAccessFile that rolls by time and file size has a great performance improvement compared to RollingFileAppender. The official website claims that it is 20-200%.
Rolling means that when certain conditions are met, the original log file is renamed for backup and a new log file is generated. For example, the requirement is to generate a log file every day, but if the volume of the log file in a day has exceeded 1G, it is generated again, and only one of the two conditions is satisfied. This is not possible in log4j 1.x native functions, it is very simple in log4j2.
The specific meaning
<properties> defines two constants to facilitate subsequent reuse

The attributes of 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 greater than the value specified by size, the Rolling is triggered.
DefaultRolloverStrategy specifies the maximum number of files to save
TimeBasedTriggeringPolicy This configuration needs to be used in conjunction with filePattern. Note that the file renaming rule configured in filePattern is ${FILE_NAME}-%d{yyyy-MM-dd HH-mm}-%i. The smallest time granularity is mm, that is, minutes. The size specified by TimeBasedTriggeringPolicy is 1, and when combined, a new file is generated every 1 minute. If it is changed to %d{yyyy-MM-dd HH} and the minimum granularity is hour, then a file will be generated every hour.

5. It is very simple to use,
first introduce the class

  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;

Declare in the class

protected transient Logger logger = LoggerFactory.getLogger(getClass());

** 6 ** Chinese garbled if the console, try the code below into
the

<PatternLayout charset="GB18030"  pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />

charset="GB18030" Change UTF-8 to GB18030. If the console is garbled, modify the PatternLayout of the console. If the output file is garbled, modify the PatternLayout of the file to
solve the problem.

You can refer to
the perfect solution for using Slf4j to integrate Log4j2 to build a project log system

Guess you like

Origin blog.csdn.net/u011930054/article/details/88412063