这篇我们来学习spring_boot的日志使用
一,spring-boot默认支持logback,可以直接在application.properties中添加:
logging.file=./springboot.log
logging.level.org.springframework.web=INFO
查看本地日志文件目录:H:\project\demo\springboot.log,确实存在
二, 使用logback.xml配置方式:
1,在 src/main/resources 下面创建logback.xml文件。
2,想使用spring扩展profile支持,要以logback-spring.xml命名
3,logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<logger name="org.springframework.web" level="INFO"/>
<logger name="org.springboot.sample" level="TRACE" />
<!-- 测试环境+开发环境. 多个使用逗号隔开. -->
<springProfile name="test,dev">
<logger name="org.springframework.web" level="DEBUG"/>
<logger name="org.springboot.sample" level="DEBUG" />
<logger name="com.example" level="DEBUG" />
</springProfile>
<!-- 生产环境. -->
<springProfile name="prod">
<logger name="org.springframework.web" level="ERROR"/>
<logger name="org.springboot.sample" level="ERROR" />
<logger name="com.example" level="ERROR" />
</springProfile>
</configuration>
这里说明一下:
1) 引入的base.xml是Spring Boot的日志系统预先定义了一些系统变量的基础配置文件
2)在application.properties中设置环境为prod,则只会打印error级别日志
3) 如果在application.properties中定义了相同的配置,则application.properties的日志优先级更高
========================================================================================================
关于多环境的配置说明:
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识
这里如果我们想启用prod生产环境的配置,只需要新建一个application-prod.properties,这个配置文件可以配置生产环境所需的配置项
然后在application.properties里面加入一行代码:
spring.profiles.active=prod
四,测试:HelloController
package com.example.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RestController
public class HelloController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping("/sayHello")
public String sayHello(String name){
logger.info("default info logging");
logger.debug("dev debug logging");
logger.error("prod error logging");
return "Hello: "+name;
}
}
启动查看控制台,打印error级别日志:
2017-04-10 16:23:41.505 ERROR 7856 --- [nio-8088-exec-1] com.example.controller.HelloController : prod error logging
如果在application.properties中添加:
logging.level.com.example.controller=INFO
则打印日志:
2017-04-10 16:29:18.047 INFO 7076 --- [nio-8088-exec-1] com.example.controller.HelloController : default info logging
2017-04-10 16:29:18.048 ERROR 7076 --- [nio-8088-exec-1] com.example.controller.HelloController : prod error logging
下篇继续学习与日志有关的,使用AOP记录日志,SpringBoot 学习记录(五): aop记录日志