一、默认配置
@SpringBootTestclass Springboot0414ApplicationTests {//记录器Logger logger = LoggerFactory.getLogger(getClass());@Testpublic void contextLoads() {System.out.println("system.out 日志...");// 日志的级别由低到高 trace<debug<info<warn<error// 可以调整输出的日志级别,日志就只会在这个级别及以后的高级别生效logger.trace("这是trace日志...");logger.debug("这是debug日志...");// SpringBoot默认使用info级别的日志,// 如果没有指定日志级别就使用Spring Boot默认的日志级别(root级别)logger.info("这是info日志...");logger.warn("这是warn日志...");logger.error("这是error日志...");}}
日志输出格式:%d表示日期时间%thread表示线程名%-5level:级别从左显示5个字符宽度%logger{50} 表示logger名字最长50个字符,否则按照句点分割%msg:日志消息%n是换行符例如: %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
二、Spring Boot修改日志默认配置
## 给com.gmd下目录设置debug日志级别logging.level.com.gmd=debug## 不指定路径在当前项目下生成springboot.log日志,指定完整的路径则在对应的路径下生成logging.file=/home/gmd/springboot.log## 不设置logging.file仅设置logging.path,则在当前磁盘的根路径下创建spring文件夹和里面的log文件夹,使用 spring.log 作为默认文件logging.path=/spring/log## 在控制台输出的日志的格式logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n## 指定文件中日志输出的格式logging.pattern.file=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
| logging.file | logging.path | 实例 | 说明 |
|---|---|---|---|
| null | null | 只在控制台输出 | |
| 指定文件名 | null | /home/log/my.log | 输出日志到/home/log/my.log |
| null | 指定目录 | /home/log | 输出日志到/home/log/spring.log |
| 指定文件名 | 指定目录 | /home/log/my.log /home/gmd |
logging.file生效,输出日志到/home/log/my.log |
三、指定日志配置文件
在类路径下生成每个日志框架的配置文件即可,SpringBoot就不使用他默认配置的了
| 日志框架 | 配置文件名 |
|---|---|
| Logback | logback-spring.xml、logback-spring.groovy、 logback.xml、logback.groovy |
| Log4j2 | log4j2-spring.xml、log4j2.xml |
| JUL | logging.properties |
配置文件名带了
spring标识,则有Spring Boot解析配置,没有带则有该日志框架本身解析。
例如:
logback.xml:直接就被Logback日志框架识别
logback-spring.xml:日志框架识别不了,由SpringBoot解析日志配置,可以使用Spring Boot的高级Profile功能
<!--高级Profile功能 可以指定某段配置只在某个环境下生效--><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>
<!--日志配置文件实例--><appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"><layout class="ch.qos.logback.classic.PatternLayout"><!--开发环境日志配置--><springProfile name="dev"><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern></springProfile><!--非开发环境日志配置--><springProfile name="!dev"><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern></springProfile></layout></appender>
如果使用logback.xml作为日志配置文件,还要使用profile功能,则会报错。
