Spring Boot 整合 logback 实现日志管理

╰+攻爆jí腚メ 2024-02-18 16:16 127阅读 0赞

摘要:前面两篇介绍了Spring Boot 整合 log4j,log4j2 实现日志管理,这篇介绍下Spring Boot 整合 logback实现日志管理,其实很简单,因为Spring Boot 默认实现的日志管理就是使用的logback。

一:新建java工程,如下图:

Center

二:添加pom.xml配置文件,这里只需添加Spring Boot的web模块即可,不需要添加任何日志依赖,因为Spring Boot web模块已经实现了logback日志模块,如下:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <groupId>com.micai</groupId>
  4. <artifactId>micai-springboot-logback-10</artifactId>
  5. <version>1.0-SNAPSHOT</version>
  6. <modelVersion>4.0.0</modelVersion>
  7. <packaging>jar</packaging>
  8. <name>micai-springboot-logback-10</name>
  9. <url>http://maven.apache.org</url>
  10. <!-- Spring Boot 启动父依赖 -->
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>1.5.1.RELEASE</version>
  15. </parent>
  16. <dependencies>
  17. <!-- Spring Boot web依赖,Spring Boot默认使用的就是logback日志管理 -->
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-web</artifactId>
  21. </dependency>
  22. </dependencies>
  23. </project>

三:新建logback-spring.xml配置文件,如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3. <include resource="org/springframework/boot/logging/logback/base.xml" />
  4. <logger name="com.micai.springboot" level="DEBUG" />
  5. <springProfile name="staging">
  6. <logger name="com.micai.springboot" level="TRACE" />
  7. </springProfile>
  8. </configuration>

四:在java类中使用logback日志模块,如下:

  1. package com.micai.springboot.web;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. /**
  7. * @author zhaoxinguo on 2017/8/21.
  8. */
  9. @RestController //提供实现了REST API,可以服务JSON,XML或者其他。这里是以String的形式渲染出结果。
  10. public class HelloWorldController {
  11. private Logger logger = LoggerFactory.getLogger(this.getClass());
  12. @RequestMapping("/") //提供路由信息,”/“路径的HTTP Request都会被映射到sayHello方法进行处理。
  13. public String sayHello(){
  14. logger.debug("Sample Debug Message");
  15. logger.trace("Sample Trace Message");
  16. return "Hello,World!";
  17. }
  18. }

源代码地址: https://gitee.com/micai/micai-springboot/tree/master/micai-springboot-logback-10

发表评论

表情:
评论列表 (有 0 条评论,127人围观)

还没有评论,来说两句吧...

相关阅读