Spring Boot入门(13):日志

一、日志

1、日志框架(推荐)

(1)日志门面(相当于Java抽象类):SLF4j
(2)日志实现(相当于抽象类的具体实现):LogBack
(3)SpringBoot选用 SLF4j和LogBack。

2、使用日志

(1)开发时候不是调用日志具体实现类,而是调用日志门面。(下面为官方文档),application 调用日志门面slf4j-api.jar,日志门面调用具体的实现类logback-calssic.jar。
在这里插入图片描述

	import org.slf4j.Logger;
	import org.slf4j.LoggerFactory;
	
	public class HelloWorld {
	  public static void main(String[] args) {
	    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
	    logger.info(()->"Hello World");
	  }
	}

3、各种框架统一为SLF4j

(1)如果系统中使用了Spring,MyBatis技术,这些技术用了不同的日志框架,也可以统一使用SLF4j进行输出。
(2)左面一列是SLF4j+LogBack实现流程。
(3)假设项目中使用了Commons logging API日志框架,SLF4j通过一个jcl-over-slf4j.jar包覆盖原来的,覆盖的jar包包含原来的框架的所有类,而且具体的实现功能通过调用LogBack.jar实现具体的内容,这样就实现了各种框架的统一输出日志。
在这里插入图片描述

4、SpringBoot中的日志依赖关系

(1)、通过在pom.xml右键->Diagrams->Show Dependencies查看依赖关系框图。
(2)、可以明显看出来依赖关系。
在这里插入图片描述

5、引入其他框架的时候一定要把默认依赖排除掉

例如SpringBoot引入spring框架,spring框架默认使用commons-logging日志框架,需要在pom.xml中将其排除掉。

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<exclusions>
		<exclusion>
			<groupId>commons-logging</groupId>
			<artfactId>commons-logging</artfactId>
		</exclusion>
	</exclusions>
</dependency>

6、日志的记录输出方法

(1)、级别由低到高为:trace<debug<info<warn<error。
(2)、SpringBoot默认给我们使用的级别是info级别,可以在配置文件中修改。
(3)、现在的jdk版本要求logger.info(Supplier supplier)所有的方法传入的参数为函数式接口。可以用()->代替参数Supplier

	class SpringBootAutoconfigApplicationTests {
	    Logger logger = LoggerFactory.getLogger(getClass());
	
	    @Test
	    public void contextLoads() {
	        logger.trace(()->"trace 日志");
	        logger.debug(()->"debug日志");
	        logger.info(()->"info 日志");
	        logger.warn(()->"warn日志");
	        logger.error(()->"error日志");
	
	    }
	
	}

7、日志的配置

(1)使用logging.level.com.hu = trace:将com.hu中的文件都调整级别为trace
(2)指定日志文件位置
(3)若不使用默认的配置文件只要需要去SpringBoot官网将对应框架的xml文件放入项目中。推荐使用logback-spring.xml
Spring Boot官网描述
在这里插入图片描述

	logging.level.com.hu = trace
	
	// logging.file = my.log
	
	logging.path = /spring/log

(4)日志的多环境支持:SpringProfile

	<springProfile name="staging">
	    <!-- configuration to be enabled when the "staging" profile is active -->
	</springProfile>
	
	<springProfile name="dev | staging">
	    <!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
	</springProfile>
	
	<springProfile name="!production">
	    <!-- configuration to be enabled when the "production" profile is not active -->
	</springProfile>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

coder鹏鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值