Springboot tool article: log4j2 integrated, easier to use with lombok

For a system, the log is a very important part of the log can help us to quickly find the relevant system abnormalities that can help developers to debug the program, you can program the operation of the monitoring system, the log is divided into different levels (I am more commonly used is the debug , info, error, remaining much to say, interested can check the Internet to find the log levels). While the log is very important to us, but as developers still do not want to spend too much code in the log above. Ado, let's look at how to integrate log4j2 in springboot project and how to combine lombok make the code more concise.

1. pom.xml file, add log4j2 and lombok dependence

Remove springboot default logging configuration:


4055666-3f8d5f4c9134584a.png
image.png

Add maven dependence

     <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>
<!-- 引入log4j2依赖 -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-log4j2</artifactId>
      </dependency>
      <!--引入lombok依赖-->
      <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.18.4</version>
          <scope>provided</scope>
      </dependency>

2. Create a profile log4j2

The following resources created in the directory configuration file named log4j2-spring.xml (note the file name, so we do not need to add a configuration file application.properties).
Configuration file as follows (document were not described in detail here):

<?xml version="1.0" encoding="UTF-8"?>
<!--设置log4j2的自身log级别为warn-->
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,
    当设置成trace时,你会看到log4j2内部各种详细输出-->
<!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
<configuration status="warn" monitorInterval="30">
    <!--先定义所有的appender-->
    <appenders>
        <!--这个输出控制台的配置-->
        <console name="Console" target="SYSTEM_OUT">
            <!--输出日志的格式-->
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </console>
        <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用-->
        <File name="log" fileName="log/test.log" append="false">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </File>
        <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,
        则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
        <RollingFile name="RollingFileInfo" fileName="${sys:user.home}/logs/hpaasvc/info.log"
                     filePattern="${sys:user.home}/logs/hpaasvc/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <Filters>
                <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
                <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
                <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"/>
            </Filters>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        </RollingFile>
 
        <RollingFile name="RollingFileWarn" fileName="${sys:user.home}/logs/hpaasvc/warn.log"
                     filePattern="${sys:user.home}/logs/hpaasvc/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
            <Filters>
                <ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
                <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"/>
            </Filters>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
            <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
 
        <RollingFile name="RollingFileError" fileName="${sys:user.home}/logs/hpaasvc/error.log"
                     filePattern="${sys:user.home}/logs/hpaasvc/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="ERROR"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        </RollingFile>
 
    </appenders>
    <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
    <loggers>
        <!--过滤掉spring和hibernate的一些无用的debug信息-->
        <logger name="org.springframework" level="INFO">
        </logger>
        <logger name="org.mybatis" level="INFO">
        </logger>
        <root level="all">
            <appender-ref ref="Console"/>
            <!--<appender-ref ref="RollingFileInfo"/>-->
            <!--<appender-ref ref="RollingFileWarn"/>-->
            <!--<appender-ref ref="RollingFileError"/>-->
        </root>
    </loggers>
</configuration>

3. Add lombok plug

Click the idea of file -> Settings -> Plugins then search box lombok
restart after installation is complete idea to

4. log4j2 and lombok

Log4j2 now only need to add annotations @ Slf4j related to the above category (provided by the annotation Lombok)
specific code as follows:
DemoController.java

package com.example.study3;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping
@RestController
@Slf4j
public class LogController {

    @GetMapping("/getTest")
    public String getTest(){
        log.info("测试方法");
        return "hello,this is zhngxian's demo";
    }

    @GetMapping("/getPerson")
    public PersonDto person() {
        log.info("查询人员信息开始-------");
        PersonDto personDto = new PersonDto();
        personDto.setName("张三丰");
        personDto.setAge(120);
        personDto.setSex("男");
        personDto.setAddress("武当山");
        log.info("查询人员信息结束-------");
        return personDto;
    }
}

PersonDto.java (@Data lombok also provided, eliminating the need for entity class getter and setter methods, the code is more concise, compile time will automatically generate getter and setter methods)

package com.example.demo.controller.dto;
 
import lombok.Data;
 
@Data
public class PersonDto {
    private String name;
    private int age;
    private String sex;
    private String address;
}

Start the project, the log is no longer the original default format:

4055666-b5436a171bfa0e09.png
image.png

Test controller in the log, enter in your browser: HTTP: // localhost: 8080 / getPerson
4055666-374bc666f4d4614d.png
image.png

4055666-c6c375becc0013e7.png
image.png

Guess you like

Origin blog.csdn.net/weixin_34211761/article/details/90783083