要使用 SOFABoot,需要先准备好基础环境,SOFABoot 依赖以下环境:

  • JDK7 或 JDK8
  • 需要采用 Apache Maven 3.2.5 或者以上的版本来编译

创建工程

SOFABoot 是直接构建在 Spring Boot 之上,因此可以使用 来生成,在本文档中,我们需要添加一个 Web 的依赖同时编写一个简单的 REST 服务,以便最后在浏览器中查看效果。

在创建好一个 Spring Boot 的工程之后,接下来就需要引入 SOFABoot 的依赖,首先,需要将上文中生成的 Spring Boot 工程的 包解压后,修改 Maven 项目的配置文件 pom.xml,将

  1. <parent>
  2. <groupId>com.alipay.sofa</groupId>
  3. <artifactId>sofaboot-dependencies</artifactId>
  4. <version>${sofa.boot.version}</version>
  5. </parent>

这里的 ${sofa.boot.version} 指定具体的 SOFABoot 最新版本,参考发布历史

然后,添加一个 SOFATracer 依赖:

  1. <dependency>
  2. <groupId>com.alipay.sofa</groupId>
  3. <artifactId>tracer-sofa-boot-starter</artifactId>
  4. </dependency>

最后,在工程的 application.properties 文件下添加一个 SOFATracer 要使用的参数,包括spring.application.name 用于标示当前应用的名称;logging.path 用于指定日志的输出目录。

添加一个最简单的 Controller

  1. @RestController
  2. private static final String TEMPLATE = "Hello, %s!";
  3. private final AtomicLong counter = new AtomicLong();
  4. /**
  5. * http://localhost:8080/springmvc
  6. * @param name name
  7. * @return map
  8. */
  9. @RequestMapping("/springmvc")
  10. public Map<String, Object> springmvc(@RequestParam(value = "name", defaultValue = "SOFATracer SpringMVC DEMO") String name) {
  11. resultMap.put("success", true);
  12. resultMap.put("id", counter.incrementAndGet());
  13. resultMap.put("content", String.format(TEMPLATE, name));
  14. }
  15. }

可以将工程导入到 IDE 中运行生成的工程里面中的 main 方法(一般上在 XXXApplication 这个类中)启动应用,也可以直接在该工程的根目录下运行 mvn spring-boot:run,将会在控制台中看到启动打印的日志:

  1. 2018-05-11 11:55:11.932 INFO 66490 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'SpringMvcOpenTracingFilter' to urls: [/*]
  2. 2018-05-11 11:55:13.961 INFO 66490 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
  3. 2018-05-11 11:55:13.970 INFO 66490 --- [ main] c.a.s.t.e.springmvc.DemoApplication : Started DemoApplication in 8.361 seconds (JVM running for 9.34)

可以通过在浏览器中输入 http://localhost:8080/springmvc 来访问 REST 服务,结果类似如下:

查看日志

在上面的 application.properties 里面,我们配置的日志打印目录是 ./logs 即当前应用的根目录(我们可以根据自己的实践需要配置),在当前工程的根目录下可以看到类似如下结构的日志文件:

  1. ./logs
  2. ├── spring.log
  3. └── tracelog
  4. ├── spring-mvc-digest.log
  5. ├── spring-mvc-stat.log
  6. ├── static-info.log
  1. {"time":"2018-05-17 22:20:34.279","local.app":"SOFATracerSpringMVC","traceId":"0a0fe9391526566833985100139443","spanId":"0","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":69,"time.cost.milliseconds":284,"current.thread.name":"http-nio-8080-exec-1","baggage":""}

附此示例工程的源代码地址