Spring Series (7) --- Two ways of SpringBoot custom printing logs

1 Get the log object first, and then use the methods provided by the log object to print the log

@Controller
@ResponseBody
public class LoggerController {
    
    
    // 1. 得到日志对象(来自 slf4)
    // 设置当前类的类型(+ LoggerController.class)
    private final static Logger log =
            LoggerFactory.getLogger(LoggerController.class);
    @RequestMapping("/sayHi")
    public void sayHi() {
    
    
        // 2. 使用日志对象提供的打印方法进行日志打印
        log.trace("我是 trace");
        log.debug("我是 debug");
        log.info("我是 info");
        log.warn("我是 ware");
        log.error("我是 error");
    }
}

operation result:
insert image description here

log level:

insert image description here
There are also two ways to set up log persistence:

  • Method 1: Set the save path of the log (the path is best copied by yourself), and SpringBoot will generate log files in its own format to the corresponding directory;
  • Method 2: This is the save file name of the log, and SpringBoot will save the log according to the set file;

insert image description here

The result shows:
Method 1:
insert image description here
Method 2:
insert image description here


Set global and local log levels:

insert image description here
When there is a local log level and a global log level, the local log level is used when accessing the local log, that is, the level priority of the local log > the global log level.


2 Use @slf4j annotation (easier)

Step 1: Add dependencies;

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

Step 2: Add @slf4j annotation;

@Service
@Controller  // 他是与前端进行交互的, 因此如果不加 @Controller 的话, 他是访问不到 sayHo 的.
@ResponseBody
@Slf4j
public class LoggerService {
    
    
    @RequestMapping("/sayHo")
    public void sayHo() {
    
    
        log.trace("1是 trace");
        log.debug("2是 debug");
        log.info("3是 info");
        log.error("4是 error");
    }
}

operation result:
insert image description here

Guess you like

Origin blog.csdn.net/Onion_521257/article/details/129853419