springboot 使用logback记录日志,并简单配置application.properties

1.在application.properties配置文件中追加

# log配置 自动按天切割日志
#level.指定root是所有目录,也可以指定包命名空间,value是记录日志的等级,从低到高,如果记录的等级低于当前配置的等级,日志就不会被记录
logging.level.root=debug
# 文件相对位置以及文件名,网上教程配置文件路径logging.file,我现在用的不推荐那样设置
logging.file.name=logs/web.log
# 日志文件保存天数
logging.file.max-history=1024

2.在需要记录的类中加入

package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import org.springframework.web.bind.annotation.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//@Controller
@RestController
public class SoupDataSource {
        // 初始化对象,参数SoupDataSource为当前调用日志的类名
    public static final Logger LOGGER = LoggerFactory.getLogger(SoupDataSource.class);
    
    @RequestMapping("/hehe")
    public String gg(){
        LOGGER.debug("This is a debug message");//注意 spring 默认日志输出级别为 info 所以默认情况下 这句不会打印到控制台
        LOGGER.info("This is an info message");
        LOGGER.warn("This is a warn message");
        LOGGER.error("This is an error message");
        return "hello";
    }
}

3.访问/hehe后在项目根目录下 logs/web.log可以看到记录的日志,过去当前天之后日志会自动切割

备注:

  mall4j 电商项目中描述了把日志封装为注解(没有测试实践,并不太理解),这样就能够精简代码了吧 

参考:

  https://blog.csdn.net/lchq1995/article/details/80080642  springboot日志输出到文件

  https://m.imooc.com/qadetail/229203  Spring Boot支持日志文件按日期切分吗?

  https://blog.csdn.net/qtdywp/article/details/84940537 Spring Boot:配置logging日志及输出日志

  https://gitee.com/gz-yami/mall4j  mall4j 电商商城系统

如果觉得文章对您有帮助,希望您能 关注+推荐 哦
原文地址:https://www.cnblogs.com/xiaqiuchu/p/14333084.html