日志在系统中相当重要,尤为是生产环境,一旦出现问题,首先是日志中的错误信息触发预警系统,而后经过邮件、短信甚至电话通知的方式报警给系统负责人。在排查修复问题阶段,开发测试人员一般也要查看系统日志,分析故障缘由。
java
Spring默认使用SLF4J和LogBack,可在application.yml中定制配置。git
代码文件github |
功能要点web |
|
SpringBoot集成SLF4J和LogBackspring |
pom.xml缓存 |
引入log依赖:spring-boot-starter-logging,注:spring-boot-starter和spring-boot-starter-web已经引入了spring-boot-starter-loggingapp |
application.ymlide |
定制配置log属性函数 |
|
封装LogUtilspring-boot |
LogUtil.java |
集中处理日志 |
单元测试 |
LogUtilTest.java |
测试log输出 |
功能调用 |
xxx.java |
调用LogUtil函数,如LogUtil.info() |
l 代码
Github下载:https://github.com/jextop/StarterApi/
l SpringBoot集成Log日志
1. pring-boot-starter和spring-boot-starter-web默认引入了SLF4J和LogBack依赖。若是须要单独引入,可在pom.xml中添加spring-boot-starter-logging
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
2. 在application.yml中定制配置log属性:
logging.level:指定package的输出日志级别,可选:debug, info, warn, error
logging.file.path:指定日志文件路径
logging.file.max-size:指定单个文件大小,超过期将滚动生成多个文件
logging.file.max-history:指定归档日志文件保留的最长历史记录
logging.pattern.console:输出到console工做台的日志格式
logging.pattern.file:输出到日志文件的格式
logging:
level:
com.starter: info
file:
path: logs
max-size: 10MB
max-history: 7
pattern:
console: "%d %-5level [%thread] %logger : %msg%n"
file: "%d %-5level [%thread] %logger : %msg%n"
l 封装LogUtil.java,集中处理日志
l 单元测试,调用LogUtil
@SpringBootTest(classes = StarterApplication.class)
public class LogUtilTest {
@Test
public void testLog() {
LogUtil.debug("debug", "message.");
LogUtil.info("info", "message.");
LogUtil.warn("warn", "message.");
LogUtil.error("error", "message.");
}
}
输出日志:
2020-01-31 14:21:13,796 INFO [main] com.common.util.LogUtil : info, message.
2020-01-31 14:21:13,796 WARN [main] com.common.util.LogUtil : warn, message.
2020-01-31 14:21:13,796 ERROR [main] com.common.util.LogUtil : error, message.
l 功能调用
- 代码中调用LogUtil.info(“xxx”)
LogUtil.info("Check cache to set str", key, str);
- Console工做台和日志文件输出:
2020-01-31 14:19:02,438 INFO [http-nio-8011-exec-2] com.common.util.LogUtil : Check cache to set str, cache_test_192.168.3.9_200131014871354985900257_缓存, cache_test_192.168.3.9_200131014871354985900257_缓存