SpringBoot 微信点餐系统 3:使用日志

门面 Slf4j,实现 logback

日志测试用例

 @RunWith(SpringRunner.class)
@SpringBootTest
public class LoggerTest{
    // 注意这里填写的哪个类就会打印出哪个类
    private final Logger logger = LoggerFactory.getLogger(LoggerTest.class);
  }
  
  @Test
  public void test1(){
      logger.debug("this is debug test");
      logger.info("this is info test");
  }

运行时会发现不会打出 debug 的信息,因为默认是 info级别的,如果想打印 debug,需要到 application.properties 中 设置 debug = true.

使用 lombok 简化操作

配置即使用可见, https://www.jianshu.com/p/3f69996e17f3

日志输出变量

logger.info("this is a good start,{}", "jack");

Logback 的配置

1. 直接在 application.yml 下配置

  • 如果有目录则在目录下输出日志,如果目录不存在则在工程文件所在的根目录下创建目录
  • 日志文件名默认为 spring.log, 也可以使用 file 指定文件名
logging:
  pattern:
    console: "%d - %msg%n"
    path: var/log/tomcat/
    # file: var/log/tomcat/sell.log
    level: debug

2. 使用文件配置

resources 下新建文件,logback-spring.xml.不需要在其他的地方配置路径,可见 spring 会扫描 resource 下面的资源。

  1. 在文件中配置 console



    
    
        
        
            
            
                %d - %msg%n
            
        
    

    
    
        
        
    

  1. 配置日志输出的文件
    
    
        
            
            
                %msg%n
            
        
        
        
            
            /var/log/tomcat/sell/info.%d.log
        
    

然后把这个配置添加到 root 下面,表示在全局范围内使用

    
        
        
        
    
  1. error/info 输出到不同的文件中
    1. 先创建一个error文件的配置
    
        
            
            
                %msg%n
            
        
        
        
            
            /var/log/tomcat/sell/error.%d.log
        
    

然后将此配置添加到 root 中。


  1. error文件中 只写入error信息. 在error 的配置中,添加这个子项。
        
            ERROR
        

如果把这个配置写入到 info 的配置中,那么就会发现 info 文件中依然存在 error 日志,这是因为这个配置只会过滤 level >= 当前级别,因为 error 的级别比 info 更高,所以会写入到 info 文件中。

  1. info 文件中只显示 info 日志.
    遇到 ERROR 就会拒绝,不匹配就会接受。
        
            ERROR
            DENY
            ACCEPT
        

因为只过滤 ERROR 日志,所以如果如果有 warn 日志,也是会写到 info 文件中的。

SpringBoot 的默认日志

路径: C:\Users\Administrator.m2\repository\org\springframework\boot\spring-boot\2.0.0.RELEASE\spring-boot-2.0.0.RELEASE.jar!\org\springframework\boot\logging\logback

你可能感兴趣的:(SpringBoot 微信点餐系统 3:使用日志)