Log4j2 log is simple to use

log4j2 log usage

1. Introduction to log4j2

Apache Log4j2 is an upgraded version of Log4j.
Log4j2 draws on some excellent designs of logback and fixes some problems, thus bringing some major improvements, mainly including: 1.
Exception handling: in logback, exceptions in Appender It will not be noticed by the application, but some exception handling mechanisms are provided in log4j2.
2. Performance improvement: Compared with log4j 1 and logback, log4j2 has obvious performance improvement, which is about 10 times that of logback under asynchronous configuration.
3. Automatic reload configuration: Referring to the design of logback, it provides automatic refresh parameter configuration, which can dynamically modify the log level without restarting the application.
4. Garbage-free mechanism. In most cases, log4j2 can use its designed garbage-free mechanism to avoid jvm gc caused by frequent log collection.

For details, please refer to its official documentation: http://logging.apache.org/log4j/2.x/manual/configuration.html

Log4j2 can be used as either a log implementation or a log facade. However, in daily development, it is customary to use log4j2 as a log implementation and slf4j as a log facade.

2. Practice

2.1 pom dependency

  1. If it is a test of a local maven project:

    After 2.9, a new display format for process numbers is added:%processId

    As a log facade and to implement ****, log4j2 needs to import the following dependencies:

    <dependencies>
        <!--log4j依赖:api和core-->
        <!--log4j日志门面-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.13.3</version>
        </dependency>
        <!--log4j日志实现-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3</version>
        </dependency>
    </dependencies>
    
    
    

    slf4j serves as the log facade, and log4j2 serves as the required import dependencies for log implementation:

    <dependencies>
        <!--使用slf4j作为日志门面-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.28</version>
        </dependency>
        <!--使用log4j的适配器进行绑定-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.9.1</version>
        </dependency>
        <!--log4j日志实现-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3 </version>
        </dependency>
    </dependencies>
    
  2. If it is a Springboot project, you need to quote the following dependencies:

    If the spring-boot-starter-web dependency package is imported into the project, remember to remove spring's own log dependency spring-boot-starter-logging, as follows:

    <dependencies>
       <!--springboot工程需要使用的log4j2的依赖--> 
    	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
     	<!--如果引用由web的依赖,需要排除掉spring自带的logging日志依赖-->   
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>    
    
    

2.2 Configuration file

After adding the above dependencies, you need to add a configuration file log4j2.xmland place it in resourcesthe directory:

<?xml version="1.0" encoding="UTF-8"?>
<!-- status表示设置的日志级别,高于该级别的日志显示,monitorInterval配置成一个正整数,则每隔指定的时间(秒),
        log4j2会刷新一次配置。如果不配置则不会动态刷新 -->
<configuration status="info" monitorInterval="600" >

    <properties>
        <property name="LOG_HOME">./logs</property>
        <!--info日志的标准输出文件名字-->
        <property name="FILE_NAME_INFO">std</property>
        <!--error日志的标准输出文件名字-->
        <property name="FILE_NAME_ERROR">error</property>
        <!--日志输出的格式-->
        <!--日期时间|日志级别|所属类的全类名|线程名|进程号|方法名|日志信息-->
        <property name="PATTERN_LAYOUT">%d{yyyy-MM-dd HH:mm:ss}|%-5level|%c{5}|%t|%processId|%M|%m%n</property>
    </properties>
    <!--先定义所有的appender -->
    <Appenders>
        <!--这个输出控制台的配置 -->
        <Console name="Console" target="SYSTEM_OUT">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
            <ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
            <!--输出日志的格式 引用定义的格式-->
            <PatternLayout pattern="${PATTERN_LAYOUT}"/>
        </Console>

        <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
        <!--append为true表示消息追加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true -->
        <RollingRandomAccessFile   name="info" fileName="${LOG_HOME}/${FILE_NAME_INFO}.log" append="true"
                                   filePattern="${LOG_HOME}/${FILE_NAME_INFO}.log.%d{yyyy-MM-dd}">
            <Policies>
                <!--TimeBasedTriggeringPolicy :时间滚动策略,默认0点小时产生新的文件, modulate="true" : 产生文件是否以0点偏移时间-->
                <TimeBasedTriggeringPolicy/>
            </Policies>
            <!--       日志输出格式     -->
            <PatternLayout pattern="${PATTERN_LAYOUT}"/>
        </RollingRandomAccessFile  >

        <!--添加过滤器Filters,可以有选择的输出某个级别以上的类别  onMatch="ACCEPT" onMismatch="DENY"意思是匹配就接受,否则直接拒绝  -->
        <RollingRandomAccessFile   name="error" fileName="${LOG_HOME}/${FILE_NAME_ERROR}.log"
                                   filePattern="${LOG_HOME}/${FILE_NAME_ERROR}.log.%d{yyyy-MM-dd}">
            <Policies>
                <!--TimeBasedTriggeringPolicy :时间滚动策略,默认0点小时产生新的文件, modulate="true" : 产生文件是否以0点偏移时间-->
                <TimeBasedTriggeringPolicy/>
            </Policies>

            <Filters>
                <!--记录error级别信息 -->
                <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <!--输出日志的格式 -->
            <PatternLayout pattern="${PATTERN_LAYOUT}"/>
        </RollingRandomAccessFile  >
    </Appenders>


    <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
    <loggers>
        <root level="info">
            <appender-ref ref="Console"/>
            <appender-ref ref="error" />
            <appender-ref ref="info"/>
        </root>
        <!--向root上报这个包下的debug级别的日志-->
        <logger name = "com.kevin" level="debug" />
    </loggers>
</configuration>

2.3 Test code

package com.kevin.log4j;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;

/**
 * @Author Kevin
 * @Date 22:04 2023/4/18
 * @Description
 */
public class Log4j2Demo {
    
    

    private static  Logger log = LogManager.getLogger();
    @Test
    public void log4j2DemoTest1(){
    
    
        System.out.println("===========显示打印Debug日志信息=============");
        log.debug("log level is DEBUG:{}","this is DEBUG log...");
        
        System.out.println("===========显示打印Info日志信息=============");
        log.info("log level is INFO:{}","this is INFO log...");
        
        System.out.println("===========显示打印Warn日志信息=============");
        log.warn("log level is WARN:{}","this is WARN log...");
        
        System.out.println("===========显示打印Error日志信息=============");
        log.error("log level is ERROR:{}","this is ERROR log...");
    }
}

Insert image description here

Console output:
Insert image description here

Results in log file:
Insert image description here

Format of the configuration file: The log2j configuration file can be in xml format or json format.
The location of the configuration file: By default, log4j2 will look for files with names such as log4j2.xml, log4j.json, log4j.jsn, etc. in the classpath directory. If neither is found, it will be output according to the default configuration, that is, output to the console. You can also customize the location of the configuration file (which needs to be configured in web.xml). It is generally placed in the root directory of src/main/resources.

The name of the configuration file: must be log4j2

Personal pitfall: I configured log4j2.xml into log4j.xml. As a result, log4j2 did not find the corresponding xml configuration and output it to the console according to the default configuration: only error-level log information is displayed:
Insert image description here

2.4 Detailed explanation of configuration files

The configuration of the log4j2.xml file is roughly as follows:

  • Configuration
    • properties
    • Appenders
      • Console
        • PatternLayout
      • File
      • RollingRandomAccessFile
      • Async
    • Loggers
      • Logger
      • Root
        • AppenderRef

1. Configuration: It is the root node and has multiple attributes such as status and monitorInterval.

  • status: Used to indicate the log level that controls log4j2. The value levels from small to large are: "trace", "debug", "info", "warn", "error" and "fatal" . Only higher levels will be displayed. Logs with status value level will be displayed.
  • monitorInterval: How often the configuration file is re-read, and the configuration can be modified without restarting the application. Time unit: seconds;

2. Appenders: Output source, used to define log output.
Log4j2 supports many output sources, including Console, File, RollingRandomAccessFile, MongoDB, Flume, etc.

  • Console: Console output source, which prints logs to the console. It is usually configured during development for debugging.

  • File: file output source, writes the log to the specified file, you need to configure the input location (for example: ./app/logs)

  • RollingRandomAccessFile: This output source also writes to a file. The difference is that it is more powerful than File. You can specify that when the file reaches a certain size (such as 20MB), another file will be started to continue writing the log. Another file will involve a new file. Naming rules, so you need to configure file naming rules; this method is more practical, because you cannot keep writing to a file. If you keep writing, the file will be too large and it will freeze when opening, and it will not be convenient to find the log.

    RollingRandomAccseeFile: has the following common attributes:

    • fileName specifies the location and file name of the current log file
    • filePattern specifies the file transfer and renaming rules when Rolling occurs. Most of them use .log. time for rolling:filePattern="${LOG_HOME}/${FILE_NAME_INFO}.log.%d{yyyy-MM-dd}">
    • SizeBasedTriggeringPolicy specifies that Rolling is triggered when the file size is greater than the value specified by size.
    • DefaultRolloverStrategy specifies the maximum number of files to save
    • TimeBasedTriggeringPolicy 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, and the minimum time granularity is mm, which is minutes; If the specified size is 1, the combination will generate a new file every 1 minute. If changed to %d{yyyy-MM-dd HH}, the minimum granularity is hour, and a file will be generated every hour.

3. PatternLayout: Log output format

  • The console or file output source (Console, File, RollingRandomAccessFile) must contain a PatternLayout node, which is used to specify the format of the output file (such as the time file method line number of log output, etc.)

  • For example%d{yyyy-MM-dd HH:mm:ss}|%-5level|%c{5}|%t|%processId|%M|%m%n

  • Date and time | Log level | Full class name of the class to which it belongs | Thread name | Process number | Method name | Log information

    # 日志常用的显示格式含义:
    %c 输出所属类的全名,可写为 %c{Num} ,Num类名输出的范围 如:"com.kevin.study.DemoClass",%C{2}将使日志输出输出范围为:study.DemoClass
    %d 输出日志时间其格式为 可指定格式 如 %d{yyyy-MM-dd HH:mm:ss}等
    %l 输出日志事件发生位置,包括类目名、发生线程,在代码中的行数
    %n 换行符
    %m输出代码指定信息,如info(“message”),输出message 一般输出:%m%n放在最后
    %msg 显示日志文本
    %-5level 输出日志级别,-5表示左对齐并且固定输出5个字符,如果不足在右边补0
    %-5p 输出日志的优先级,即 FATAL ,ERROR 等; 与-5level效果一样
    %r 输出从启动到显示该条日志信息所耗费的时间(毫秒数)
    %t 输出产生该日志事件的线程名
    %processId 输出进程号,2.9之后新增
    %M 显示方法名
    

4. Loggers: Logger

Loggers are divided into: Root logger and custom logger. When the specified logger cannot be obtained according to the log name, Root is used as the default logger. When customizing, you need to specify the name of each Logger (for The naming can use the package name as the name of the log, different packages are configured with different levels, etc.), log level, additivity (whether to inherit the logger configured below), for general loggers (such as Console, File, RollingRandomAccessFile ) Generally, one or more output source AppenderRef needs to be configured;

Each logger can specify a level (TRACE, DEBUG, INFO, WARN, ERROR, ALL or OFF). If not specified, the level defaults to ERROR.

additivity specifies whether to output log to the appender of the parent class at the same time. The default is true.

5. Properties: properties
are used to define constants for reference in other configurations. This configuration is optional, for example:

  • Define the storage location of the log, under the logs folder in the current directory:<property name="LOG_HOME">./logs</property>
  • Define the output format of the log:<property name="PATTERN_LAYOUT">%d{yyyy-MM-dd HH:mm:ss}|%5p|%c{5}|%t|%processId|%M|%m%n</properties>

Guess you like

Origin blog.csdn.net/weixin_43155804/article/details/130279633