我们在springFramework中有讲过Log4J的日志框架,
在springmvc中讲过Log4J2和SLF4J等日志框架。
这次我们来讲下,怎么在springboot的框架下配置SLF4J和LogBack的使用
那么我们来了解下日志的等级:常见的分为以下5种
一.控制台输出日志、显示日志
开启日志功能:
如果你想要在springboot中开启日志功能,那么可以直接在yml配置文件中配置为:debug: true
我这里配置的是dev机:application-dev.yml:
spring:
main:
banner-mode: OFF
devtools:
restart:
enabled: true
additional-paths: src/main/java
thymeleaf:
cache: false
server:
port: 8008
servlet:
context-path: /SpringBoot
debug: true
如果我们想在自己的程序中,打上日志log,那么我们可以自己来测试下,写一个程序:
LogTestController.java:
package com.SpringBoot.demo.log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("l")
public class LogTestController {
private Logger logger = LoggerFactory.getLogger(LogTestController.class);
@GetMapping("show")
public String show() {
logger.debug("====This is debug log=========");
logger.info("========This is info log==========");
logger.error("========This is error log===========");
logger.trace("=======This is trace level log=========");
logger.warn("==========This is warn level============");
return "thymeleaf";
}
}
运行程序进行测试:
还可以设置自己想要设置的程序等级:com.SpringBoot.demo 包下的所有程序设为debug等级
spring:
main:
banner-mode: OFF
devtools:
restart:
enabled: true
additional-paths: src/main/java
thymeleaf:
cache: false
server:
port: 8008
servlet:
context-path: /SpringBoot
#debug: true
#trace: true
# package com.SpringBoot.demo 包下的所有程序设为debug等级
logging:
level:
com.SpringBoot.demo: debug
二.打印输出日志到本地文件中
在配置文件中配置下:
application-dev.yml:
name 解析: 保存路径 , name 和 path只能使用一个
max-history: 7 解析: 最大保存七天,会生成新文件
max-size: 10 解析:最大值
total-size-cap: 解析: 文件总值
clean-history-on-start 解析:启动程序是否清理日志
spring:
main:
banner-mode: OFF
devtools:
restart:
enabled: true
additional-paths: src/main/java
thymeleaf:
cache: false
server:
port: 8008
servlet:
context-path: /SpringBoot
logging:
level:
com.SpringBoot.demo: debug
file:
name: D:\logs\log_springboot.log
max-history: 7
max-size: 10MB
total-size-cap: 1GB
clean-history-on-start: FALSE
运行测试:
log_springboot.log:
2021-05-12 11:31:34.821 INFO 30456 --- [RMI TCP Connection(2)-127.0.0.1] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
2021-05-12 11:31:35.452 INFO 30456 --- [RMI TCP Connection(2)-127.0.0.1] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2021-05-12 11:31:49.748 INFO 47372 --- [main] c.S.demo.StudentTestApplication : Starting StudentTestApplication on DESKTOP-SV8H6UI with PID 47372 (D:\eclipse_SpringBoot\StudentTest\target\classes started by liyang in D:\eclipse_SpringBoot\StudentTest)
2021-05-12 11:31:49.751 DEBUG 47372 --- [main] c.S.demo.StudentTestApplication : Running with Spring Boot v2.3.10.RELEASE, Spring v5.2.14.RELEASE
2021-05-12 11:31:49.752 INFO 47372 --- [main] c.S.demo.StudentTestApplication : The following profiles are active: dev
2021-05-12 11:31:50.441 INFO 47372 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8008 (http)
2021-05-12 11:31:50.447 INFO 47372 --- [main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-05-12 11:31:50.447 INFO 47372 --- [main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.45]
2021-05-12 11:31:50.448 INFO 47372 --- [main] o.a.catalina.core.AprLifecycleListener : Loaded Apache Tomcat Native library [1.2.23] using APR version [1.7.0].
2021-05-12 11:31:50.448 INFO 47372 --- [main] o.a.catalina.core.AprLifecycleListener : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2021-05-12 11:31:50.448 INFO 47372 --- [main] o.a.catalina.core.AprLifecycleListener : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2021-05-12 11:31:50.452 INFO 47372 --- [main] o.a.catalina.core.AprLifecycleListener : OpenSSL successfully initialized [OpenSSL 1.1.1c 28 May 2019]
2021-05-12 11:31:50.514 INFO 47372 --- [main] o.a.c.c.C.[.[localhost].[/SpringBoot] : Initializing Spring embedded WebApplicationContext
2021-05-12 11:31:50.514 INFO 47372 --- [main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 724 ms
2021-05-12 11:31:50.642 INFO 47372 --- [main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-05-12 11:31:50.780 INFO 47372 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8008 (http) with context path '/SpringBoot'
2021-05-12 11:31:50.788 INFO 47372 --- [main] c.S.demo.StudentTestApplication : Started StudentTestApplication in 1.366 seconds (JVM running for 2.512)
2021-05-12 11:32:17.552 INFO 47372 --- [http-nio-8008-exec-1] o.a.c.c.C.[.[localhost].[/SpringBoot] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-05-12 11:32:17.552 INFO 47372 --- [http-nio-8008-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-05-12 11:32:17.556 INFO 47372 --- [http-nio-8008-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms
2021-05-12 11:32:17.569 DEBUG 47372 --- [http-nio-8008-exec-1] c.SpringBoot.demo.log.LogTestController : ====This is debug log=========
2021-05-12 11:32:17.570 INFO 47372 --- [http-nio-8008-exec-1] c.SpringBoot.demo.log.LogTestController : ========This is info log==========
2021-05-12 11:32:17.570 ERROR 47372 --- [http-nio-8008-exec-1] c.SpringBoot.demo.log.LogTestController : ========This is error log===========
2021-05-12 11:32:17.570 WARN 47372 --- [http-nio-8008-exec-1] c.SpringBoot.demo.log.LogTestController : ==========This is warn level============
三. 设置 ansi 彩色日志
在配置文件中设置: spring.output.ansi.enabled: always
即在application-dev.yml 设置为:
ansi 是一个插件,可以使用国际字符来采用特殊标准去显示颜色:
我们在: Help---Eclipse MarkerPlace----搜索 ansi插件,点击安装
安装成功后,重启eclipse就能显示日志颜色了
测试效果:
四. logback 自定义日志
如果我们需要根据自己的需要来自定义日志,可以通过配置文件进行自定义log功能
springboot-log.xml:
debug="false" 解析: 是否打印出configuration内部的debug日志信息,一般是默认不打印
<property name="LOG_HOME" value="./logs"/> 解析:定义log存放路径,value 是相对路径
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender"> 解析: 设置console控制台输出
FileNamePattern 标签解析: 文件名生成格式
maxHistory 标签解析: 最大7天生成新文件
</encoder> 标签解析: 日志文件的格式
filter 标签解析: 日志级别
MaxFileSize 标签解析: 文件最大值
需要先屏蔽:application.yml 中的日志输出
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<property name="LOG_HOME" value="./logs"/>
<!-- 控制台输出 -->
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<!-- <pattern>${Console_Log_Pattern}</pattern> -->
<charset>utf8</charset>
</encoder>
</appender>
<!-- INFO 文件 -->
<appender name="InfoFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${LOG_HOME}/log-info-%d{yyyy-MM-dd}.log</FileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- Error 文件 -->
<appender name="ErrorFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${LOG_HOME}/log-error-%d{yyyy-MM-dd}.log</FileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} --- %msg%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<root level="INFO">
<appender-ref ref="Console"/>
<appender-ref ref="InfoFile"/>
<appender-ref ref="ErrorFile"/>
</root>
</configuration>
运行测试:http://localhost:8008/SpringBoot/l/show
需要把这个xml文件配置到 dev配置环境中生效
logging:
config: classpath:springboot-log.xml
可以实现相同的功能, 刷新整个项目后,我们会发现在项目中有log文件,保存了相关info\error日志
五. logback 自定义 彩色日志
因为是自定义的日志,所以输出是颜色我们也是可以自定义颜色
我们只需要把彩色渲染的依赖类加入到配置文件中就可以。
日志渲染:
<conversionRule conversionWord="clr"
converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
<conversionRule conversionWord="wex"
converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
<conversionRule conversionWord="wEx"
converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
定义渲染的样板图案:
%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} 解析 : 渲染日志的时间 ,设置颜色为faint
%clr(${LOG_LEVEL_PATTERN:-%5p}) 解析: 根据不同日志级别设置不同颜色
%clr(${PID:- }){magenta} 解析:设置日志线程颜色为 magenta
<property name="Console_Log_Pattern" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr(%-40.40logger{50}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
模板的颜色定义好了,当然就要去使用到控制台中了。
<pattern>${Console_Log_Pattern}</pattern> 解析:应用图案模板
<!-- 控制台输出 -->
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<pattern>${Console_Log_Pattern}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
六. 自定义日志的扩展属性
1.多环境日志的输出
比如在实际开发中会有很多test环境,和实prod环境,以及dev环境
所以,我们的日志输出也是可以根据实际中不同的开发环境来定义日志:
<springProfile name="dev"> 解析:根据不同环境配置日志
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<property name="LOG_HOME" value="./logs"/>
<!-- <springProperty scope="context" name="LOG_HOME" source="logs.home.path" defaultValue="./logs"/> -->
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr"
converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
<conversionRule conversionWord="wex"
converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
<conversionRule conversionWord="wEx"
converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
<property name="Console_Log_Pattern" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr(%-40.40logger{50}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!-- 控制台输出 -->
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<pattern>${Console_Log_Pattern}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- INFO 文件 -->
<appender name="InfoFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${LOG_HOME}/log-info-%d{yyyy-MM-dd}.log</FileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- Error 文件 -->
<appender name="ErrorFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${LOG_HOME}/log-error-%d{yyyy-MM-dd}.log</FileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} --- %msg%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<springProfile name="dev">
<root level="INFO">
<appender-ref ref="Console"/>
<appender-ref ref="InfoFile"/>
<appender-ref ref="ErrorFile"/>
</root>
</springProfile>
<springProfile name="test | prod">
<root level="INFO">
<appender-ref ref="InfoFile"/>
<appender-ref ref="ErrorFile"/>
</root>
</springProfile>
</configuration>
也可以配置日志输出路径:
在application-dev.yml中配置输出路径:
logs:
home:
path: D:\logs
然后在xml中进行springProperty属性的配置,配置到spring容器中
解析: 如果找不到本地的保存路径,则保存到相对路径
<springProperty scope="context" name="LOG_HOME" source="logs.home.path" defaultValue="./logs"/>
运行后就能看到已经出现相关文件了