log function
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:
log level:
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;
The result shows:
Method 1:
Method 2:
Set global and local log levels:
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: