0
点赞
收藏
分享

微信扫一扫

logback日志框架基本知识

elvinyang 2023-07-02 阅读 78

文章目录


概述

在这里插入图片描述


logback简介

在这里插入图片描述

logback主要由三个模块构成:logback-core,logback-classic及logback-access

在这里插入图片描述
logback-core为基础核心,另外两个均依赖它。其中logback-classic实现了简单日志门面SLF4J;logback-access主要作为一个与Servlet容器交互的模块,提供与HTTP访问相关的一些功能。

通常使用时直接引入logback-classic的依赖,便可自动引入logback-core,当然为保险起见也可以显式的引入两者。


SpringBoot对logback的支持

上面已经提到SpringBoot默认集成了logback,因此无需专门引入便可进行直接使用。后面的示例我们也基于SpringBoot来进行演示和讲解,毕竟方便嘛。

在这里插入图片描述
我们可以看到一旦引入spring-boot-starter-web依赖,对应的不仅引入了logback框架,还同时引入了slf4j相关框架。所以,项目中直接使用即可。


SpringBoot的集成

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
package com.wideth.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(tags = "logback")
@RequestMapping("/api")
public class LogbackController {


    private static final Logger log = 
    LoggerFactory.getLogger(LogbackController.class);

    @ApiOperation(value = "logback")
    @GetMapping("/hello")
    public void hello() {

        log.debug("Hello world 测试debug日志");
        log.info("Hello world 测试info日志");
        log.warn("Hello world 测试warn日志");
        log.error("Hello world 测试error日志");
    }
}

上面代码中分别使用debug,info,warn,error方法输出日志。日志的所有配置,都是基于SpringBoot集成logback时的默认配置来的。

在这里插入图片描述

logging:
   level:
     com.wideth: debug

在这里插入图片描述


SpringBoot对logback的基础配置

logging:
   level:
     com.wideth: debug
   file:
     # 注:二者不能同时使用。否则只有logging.file生效
     name: my.log
     path: my.logs

在这里插入图片描述
在这里插入图片描述

其他的就是日志文件的大小(默认10MB)、格式,以及控制台和日志文件内日志的格式配置了。根据提示我们可以很轻易搞定。

但是,你可能也发现了在application.properties中支持的配置有些简单。对的,如果需要配置复杂的日志内容,则需要基于xml配置文件来进行操作。

在这里插入图片描述


自定义logback配置

在这里插入图片描述

也就是说如果在src/main/resources目录下放置其中任一类型的配置文件,SpringBoot便会自动进行使用。

而Spring Boot官方推荐优先使用带有-spring的文件名配置(如有logback-spring.xml,则不会使用logback.xml)。

若需要对配置文件名进行修改,或者希望把放到其它目录下,可以在application中通过logging.config属性来指定,如logging.config=classpath:config/my-log-config.xml。


本文小结

本文介绍了logback日志框架基本知识和常见的一些概念

举报

相关推荐

Shiro框架基本知识及应用

vite基本知识

MySQL基本知识

反射基本知识

0 条评论