SpringBoot学习笔记二——日志使用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_38930706/article/details/95094424

日志工具的出现是为了适应变化的日志记录需求,常用的日志工具有:JUL、JCL、Jboss-logging、logback、log4j、log4j2、slf4j......

日志类的使用可以通过对抽象类的实现来满足不同日志需求。

通常,日志门面采用slf4j,日志实现采用logback、log4j或获log4j2。

SpringBoot抛弃了Spring使用的传统JCL而选用较新的slf4j和logback组合。

怎么解决各框架使用不同抽象层日志框架的问题呢?

log4j通过狸猫换太子的方法一统日志:https://www.slf4j.org/images/legacy.png

 SpringBoot日志原理粗谈

可以看到SpringBoot使用logback作为日志记录工具,将其他类型抽象日志框架进行slf4j的转换。

SpringBoot能自动适配所有的日志,底层使用slf4j和logback的方式记录日志,引入其他框架的时候 ,只需要把这个框架依赖的日志框架移除掉,就不需要做多余的任何配置了。

SpringBoot使用slf4j

 Logger logger = LoggerFactory.getLogger(getClass());
 logger.trace("trace");
 logger.debug("debug");
 //SpringBoot默认打印info及以上级别(root)
 logger.info("info");
 logger.warn("warn");
 logger.error("error");

上面的日志级别从低到高,默认会记录info、warn、error级别的日志,修改日志级别可以通过添加配置的方式,在properties文件中加入如下配置:

logging.level.com.mlgg=trace

打印com.mlgg包下的所有级别的日志。

将日志输出到文件

官方提供的file和path的区别:

logging.file logging.path Example Description

(none)

(none)

 

Console only logging.

Specific file

(none)

my.log

Writes to the specified log file. Names can be an exact location or relative to the current directory.

(none)

Specific directory

/var/log

Writes spring.log to the specified directory. Names can be an exact location or relative to the current directory.

file将日志输出到当前项目下自定义命名文件中;path采用绝对路径,第一个斜线表示当前磁盘根目录,会在定义的目录中生成spring.log文件记录日志。

pattern

自定义日志模板

logging.pattern.file=...

logging.pattern.console=... 

SpringBoot加载的日志配置文件

Logging System Customization

Logback

logback-spring.xmllogback-spring.groovylogback.xml, or logback.groovy

Log4j2

log4j2-spring.xml or log4j2.xml

JDK (Java Util Logging)

logging.properties

logback.xml配置直接被日志框架识别;而采用logback-spring.xml命名方式不直接被识别,而是交给spring解析日志篇日志,可以使用SpringBoot的Profile功能。<springProfile> ,所以我们推荐使用后者。

切换SpringBoot的日志框架

比如我们现在使用slf4j-log4j的组合,那么我们首先需要删除log4j-to-slf4j的依赖(可以在依赖书中删除),然后加入slf4j-log4j12的依赖,再加入log4j的配置文件就OK了。但是logback是log4j的升级框架啊~

比如我们想用log4j2框架,那么需要删除logging的starter,改为log4j2的starter。

猜你喜欢

转载自blog.csdn.net/weixin_38930706/article/details/95094424