1、日志框架
市面上一些常见的日志框架:JUL、JCL、Jboss-logging、logback、log4j、log4j2、slf4j…
注意:
SpringBoot底层用的是Spring框架,而Spring框架默认用的是JCL;但是SpringBoot选用的却是SLF4j和logback。
2、SLF4j使用
(1)在SpringBoot中如何使用SLF4j
- 在开发的时候,日志记录方法的调用,不应该直接调用日志实现类,而是调用日志抽象层里面的方法;但是要导入slf4j和 logback的实现依赖
注意:
每一个日志的实现框架都有自己的配置文件。使用 slf4j 以后,配置文件还是做成日志实现框架自己本身的配置文件;
(2)不足之处
- 不同的框架有各自不同的日志框架:Spring Boot(slf4j+logback): Spring(commons-logging)、Hibernate(jboss-logging)
- 那么如何让系统中所有的日志框架都统一到SLF4j呢?
- 1、将系统中其它日志框架先排除出去
- 2、用中间包来替换原有的日志框架
- 3、再导入SLF4j其它的实现
3、SpringBoot日志关系
- 导入SpringBoot的日志依赖:
<!--引入Spring Boot的日志依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
- 其底层依赖关系如下图所示:
总结:
1)、SpringBoot底层也是使用slf4j+logback的方式进行日志记录
2)、SpringBoot也把其他的日志都替换成了slf4j;
3)、使用了中间替换包 ,其底层源码如下:
@SuppressWarnings("rawtypes")
public abstract class LogFactory {
static String UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J
= "http://www.slf4j.org/codes.html#unsupported_operation_in_jcl_over_slf4j";
static LogFactory logFactory = new SLF4JLogFactory();
4)、如果我们要引入其他框架?一定要把这个框架的默认日志依赖移除掉?
例如Spring框架用的是commons-logging;
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
5)、SpringBoot能自动适配所有的日志,而且底层使用slf4j+logback的方式记录日志,引入其他框架的时候,只需要把这个框架依赖的日志框架排除掉即可;
4、日志的使用
(1)默认配置
- SpringBoot默认帮我们配置好了日志;
//记录器
Logger logger = LoggerFactory.getLogger(getClass());
@Test
public void contextLoads() {
//日志的级别;
// 由低到高 trace<debug<info<warn<error
// 可以调整输出的日志级别;日志就只会在这个级别以以后的高级别生效
logger.trace("这是trace日志...");
logger.debug("这是debug日志...");
//SpringBoot默认给我们使用的是info级别的,没有指定级别的就用SpringBoot默认规定的级别;root 级别/
logger.info("这是info日志...");
logger.warn("这是warn日志...");
logger.error("这是error日志...");
}
- 在SpringBoot配置文件中修改日志的默认配置
logging.level.com.hcz=trace
#logging.path=
# 不指定路径在当前项目下生成springboot.log日志
# 可以指定完整的路径;
#logging.file=G:/springboot.log
# 在当前磁盘的根路径下创建spring文件夹和里面的log文件夹;使用 spring.log 作为默认文件
logging.path=/spring/log
# 在控制台输出的日志的格式
logging.pattern.console=%d{yyyy‐MM‐dd} [%thread] %‐5level %logger{50} ‐ %msg%n
# 指定文件中日志输出的格式
logging.pattern.file=%d{yyyy‐MM‐dd} === [%thread] === %‐5level === %logger{50} ==== %msg%n
(2)指定配置
- 给类路径下放上每个日志框架自己的配置文件即可;SpringBoot就不使用他默认配置的了
注意:
logback.xml:直接就被日志框架识别了;
logback-spring.xml:日志框架就不直接加载日志的配置项,由SpringBoot解析日志配置,可以使用SpringBoot的高级Profifile功能
5、项目实例
5.1 创建SpringBoot框架 Web项目
5.2 在项目 pom.xml 中添加 SSM 需要的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--连接 MySQL 的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--MyBatis 集成 SpringBoot 框架的起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!--引入SpringBoot内嵌Tomcat对jsp的解析依赖-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
5.3 编写集成 SSM 在 application.properties 的配置
server.port=8080
server.servlet.context-path=/
#设置连接数据库的配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3366/springboot
spring.datasource.username=root
spring.datasource.password=123456
# 指定 Mybatis 映射文件的路径
#mybatis.mapper-locations=classpath:mapper/*.xml
#配置视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
5.4 通过 MyBatis 逆向工程生成 DAO
这里可参考我前面Mybatis章节的Mybatis逆向工程
5.5 手动指定资源文件夹
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
5.6 编写 StudentController
@Controller
@RequestMapping(value = "/student")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "/count")
@ResponseBody
public String studentCount(){
Integer studentCount = studentService.queryStudentCount();
return "学生总人数:"+studentCount;
}
}
5.7 编写 StudentService 接口及实现类
public interface StudentService {
/**
* 获取学生总人数
* @return
*/
Integer queryStudentCount();
}
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Integer queryStudentCount() {
return studentMapper.selectStudentCount();
}
}
5.8 数据持久层
- StudentMapper.java
/**
* 获取学生总人数
* @return
*/
Integer selectStudentCount();
- StudentMapper.xml
<!--获取学生总人数-->
<select id="selectStudentCount" resultType="java.lang.Integer">
select count(*) from t_student
</select>
5.9 日志文件
Spring Boot 官方推荐优先使用带有 -spring 的文件名作为你的日志配置(如使用 logback-spring.xml ,而不是 logback.xml),命名为 logback-spring.xml 的日志配置文件。 默认的命名规则,并且放在 src/main/resources 下如果你即想完全掌控日志配置,但又不想 用 logback.xml 作为 Logback 配置的名字,application.yml 可以通过 logging.config 属性指定自 定义的名字:
logging.config=classpath:logging-config.xml
(1) 代码里打印日志
- 之前我们大多数时候自己在每个类创建日志对象去打印信息,比较麻烦:
private static final Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class);
logger.error("xxx");
现在可以直接在类上通过 @Slf4j 标签去声明式注解日志对象
A、 在 pom.xml 中添加依赖
<!--引入Spring Boot的日志依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
</dependency>
B、 添加 lombok 插件
(2) logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别从低到高分为 TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果
设置为 WARN,则低于 WARN 的信息都不会输出 -->
<!-- scan:当此属性设置为 true 时,配置文件如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认
单位是毫秒。当 scan 为 true 时,此属性生效。默认的时间间隔为 1 分钟。 -->
<!-- debug:当此属性设置为 true 时,将打印出 logback 内部日志信息,实时查看 logback
运行状态。默认值为 false。通常不打印 -->
<configuration scan="true" scanPeriod="10 seconds">
<!--输出到控制台-->
<appender name="CONSOLE"
class="ch.qos.logback.core.ConsoleAppender">
<!--此日志 appender 是为开发使用,只配置最底级别,控制台输出的日志级别是大
于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
<encoder>
<Pattern>%date [%-5p] [%thread] %logger{60}
[%file : %line] %msg%n</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--<File>/home/log/stdout.log</File>-->
<File>D:/log/springboot-logback.log</File>
<encoder>
<pattern>%date [%-5p] %thread %logger{60}
[%file : %line] %msg%n</pattern>
</encoder>
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 添加.gz 历史日志会启用压缩 大大缩小日志文件所占空间 -->
<!--<fileNamePattern>/home/log/stdout.log.%d{yyyy-MM-dd}.log</fileNam
ePattern>-->
<fileNamePattern>D:/log/springboot-logback.log.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory><!-- 保留 30 天日志 -->
</rollingPolicy>
</appender>
<logger name="com.hcz.mapper" level="DEBUG" />
<!--如果root标签指定的日志级别那么以根日志级别为准,如果没有则以当前追加器日志级别为准-->
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
5.10 Application 启动类
@SpringBootApplication
@MapperScan(basePackages = "com.hcz.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}