spring-boot通过slf4j+logback实现日志记录功能,
这里通过spring-boot的测试类,查看日志效果
SpringBootLogApplicationTests.java代码如下:package com.springboot;
import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootLogApplicationTests { Logger logger = LoggerFactory.getLogger(getClass()); @Test public void contextLoads() {
logger.trace("这是一个trace。。。"); logger.debug("this is a debug..."); logger.info("这是一个info。。。"); logger.warn("this is a warn..."); logger.error("this is a error..."); } }
这里的日志安全等级依次是:trace<debug<info<warn<error
这里的关键是: Logger logger = LoggerFactory.getLogger(getClass());
在配置文件中,我们还可以定义日志的一些高级特性高能:
application.properties:
#这里定义的是日志的安全等级的起点,默认是从info开始,也就是说:info之前的不输出
logging.level.com.springboot=trace
#这里是定义日志输出的路径,每一级都代表目录的意思,(默认)最后的日志信息放在目录的spring.log中
logging.path=/Volumes/E/springlog/log
#这里定义的是,在当前项目下生成一个log文件,log文件的名字就是自己定义的名字
logging.file=log.log
#这里定义的是日志的内容输出到文件中的格式
# %d表示日期时间,
# %thread表示线程名,
# %-5level:级别从左显示5个字符宽度
# %logger{50} 表示logger名字最长50个字符,否则按照句点分割。
# %msg:日志消息,
# %n是换行符
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} === [%thread] === %-5level === %logger{50} ==== %msg%n
#这里定义的是输出到控制台的日志格式
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} ---[%thread] --- %-5level ---%logger{50}--- %msg%n
输出效果:
【spring-boot】spring-boot项目中,实现日志记录功能(slf4j)
原文:https://www.cnblogs.com/jums/p/11323773.html