### Application Startup Log Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-mvc Observe the console logs upon starting the SOFABoot application to confirm successful initialization. ```log 2018-05-11 11:55:11.932 INFO 66490 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'SpringMvcOpenTracingFilter' to urls: [/*] 2018-05-11 11:55:13.961 INFO 66490 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 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) ``` -------------------------------- ### OkHttp Summary Log Example (JSON) Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-okhttp This is an example of the JSON output for OkHttp summary logs. It includes details like timestamp, application name, trace ID, span ID, request URL, HTTP method, result code, request/response sizes, and time cost. ```json {"time":"2019-09-03 11:35:28.429","local.app":"OkHttpDemo","traceId":"0a0fe9271567481728265100112783","spanId":"0","span.kind":"client","result.code":"200","current.thread.name":"main","time.cost.milliseconds":"164ms","request.url":"http://localhost:8081/okhttp?name=sofa","method":"GET","result.code":"200","req.size.bytes":0,"resp.size.bytes":0,"remote.app":"","sys.baggage":"","biz.baggage":""} ``` -------------------------------- ### OkHttp Statistical Log Example (JSON) Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-okhttp This example shows the JSON format for OkHttp statistical logs. It aggregates statistics based on a 'stat.key' which includes local application name, request URL, and HTTP method. It also provides request count, total cost, success status, and load test marking. ```json {"time":"2019-09-03 11:43:06.975","stat.key":{"method":"GET","local.app":"OkHttpDemo","request.url":"http://localhost:8081/okhttp?name=sofa"},"count":1,"total.cost.milliseconds":174,"success":"true","load.test":"F"} ``` -------------------------------- ### Create a RESTful Controller Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-okhttp Implement a simple RESTful controller to provide an endpoint for OkHttp calls. This example uses Spring Boot annotations. ```java @RestController public class SampleRestController { private final AtomicLong counter = new AtomicLong(0); /** * Request http://localhost:8081/okhttp?name=sofa * @param name name * @return Map of Result */ @RequestMapping("/okhttp") public Map greeting(@RequestParam(value = "name", defaultValue = "okhttp") String name) { Map map = new HashMap<>(); map.put("count", counter.incrementAndGet()); map.put("name", name); return map; } } ``` -------------------------------- ### Construct OkHttp Client Instance and Make Call Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-okhttp Instantiate an OkHttp client and execute a GET request to the previously defined RESTful service. This demonstrates making an outbound HTTP call. ```java OkHttpClientInstance httpClient = new OkHttpClientInstance(); String httpGetUrl = "http://localhost:8081/okhttp?name=sofa"; String responseStr = httpClient.executeGet(httpGetUrl); ``` -------------------------------- ### Datasource Client Stat Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-datasource Review the datasource-client-stat.log file for aggregated statistics of SQL operations, such as execution count, total cost, and success rate. ```json {"time":"2019-09-02 21:31:50.435","stat.key":{"local.app":"SOFATracerDataSource","database.name":"test","sql":"DROP TABLE IF EXISTS TEST;\nCREATE TABLE TEST(ID INT PRIMARY KEY%2C NAME VARCHAR(255));"},"count":1,"total.cost.milliseconds":15,"success":"true","load.test":"F"} ``` -------------------------------- ### Dubbo Consumer Statistics Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-dubbo Example of a JSON-formatted statistics log from a Dubbo service consumer. This log aggregates request counts and performance metrics. ```json {"time":"2019-09-02 23:36:13.040","stat.key":{"method":"SayHello","local.app":"dubbo-consumer","service":"com.glmapper.bridge.boot.service.HelloService"},"count":1,"total.cost.milliseconds":205,"success":"true","load.test":"F"} ``` -------------------------------- ### Example TraceId Format Source: https://www.sofastack.tech/projects/sofa-tracer/traceid-generated-rule A TraceId is composed of the server IP, timestamp, an incrementing sequence, and the process ID. The example shows the combined format. ```text 0ad1348f1403169275002100356696 ``` -------------------------------- ### Dubbo Provider Statistics Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-dubbo Example of a JSON-formatted statistics log from a Dubbo service provider. This log aggregates request counts and performance metrics for incoming requests. ```json {"time":"2019-09-02 23:36:13.208","stat.key":{"method":"SayHello","local.app":"dubbo-provider","service":"com.glmapper.bridge.boot.service.HelloService"},"count":1,"total.cost.milliseconds":9,"success":"true","load.test":"F"} ``` -------------------------------- ### Dubbo Consumer Digest Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-dubbo Example of a JSON-formatted digest log from a Dubbo service consumer. This log captures details about outgoing requests. ```json {"time":"2019-09-02 23:36:08.250","local.app":"dubbo-consumer","traceId":"1e27a79c156743856804410019644","spanId":"0","span.kind":"client","result.code":"00","current.thread.name":"http-nio-8080-exec-2","time.cost.milliseconds":"205ms","protocol":"dubbo","service":"com.glmapper.bridge.boot.service.HelloService","method":"SayHello","invoke.type":"sync","remote.host":"192.168.2.103","remote.port":"20880","local.host":"192.168.2.103","client.serialize.time":35,"client.deserialize.time":5,"req.size.bytes":336,"resp.size.bytes":48,"error":"","sys.baggage":"","biz.baggage":""} ``` -------------------------------- ### Dubbo Provider Digest Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-dubbo Example of a JSON-formatted digest log from a Dubbo service provider. This log captures details about incoming requests. ```json {"time":"2019-09-02 23:36:08.219","local.app":"dubbo-provider","traceId":"1e27a79c156743856804410019644","spanId":"0","span.kind":"server","result.code":"00","current.thread.name":"DubboServerHandler-192.168.2.103:20880-thread-2","time.cost.milliseconds":"9ms","protocol":"dubbo","service":"com.glmapper.bridge.boot.service.HelloService","method":"SayHello","local.host":"192.168.2.103","local.port":"62443","server.serialize.time":0,"server.deserialize.time":27,"req.size.bytes":336,"resp.size.bytes":0,"error":"","sys.baggage":"","biz.baggage":""} ``` -------------------------------- ### REST Service Response Example Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-mvc Example of the JSON response received when accessing the REST service at http://localhost:8080/springmvc. ```json { "content": "Hello, SOFATracer SpringMVC DEMO!", "id": 1, "success": true } ``` -------------------------------- ### OpenFeign Statistics Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-openfeign This is an example of a statistics log entry generated by SOFATracer for Spring Cloud OpenFeign. It aggregates request data over a period, including count, total cost, and success rate. ```json {"time":"2019-09-03 10:29:34.528","stat.key":{"method":"GET","local.app":"tracer-consumer","request.url":"http://10.15.233.39:8800/feign"},"count":2,"total.cost.milliseconds":378,"success":"true","load.test":"F"} ``` -------------------------------- ### OpenFeign Digest Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-openfeign This is an example of a digest log entry generated by SOFATracer for Spring Cloud OpenFeign. It captures detailed information about a single request. ```json {"time":"2019-09-03 10:28:52.363","local.app":"tracer-consumer","traceId":"0a0fe9271567477731347100110969","spanId":"0.1","span.kind":"client","result.code":"200","current.thread.name":"http-nio-8082-exec-1","time.cost.milliseconds":"219ms","request.url":"http://10.15.233.39:8800/feign","method":"GET","error":"","req.size.bytes":0,"resp.size.bytes":18,"remote.host":"10.15.233.39","remote.port":"8800","sys.baggage":"","biz.baggage":""} ``` -------------------------------- ### Verify SOFATracer with Sampled Requests Source: https://www.sofastack.tech/projects/sofa-tracer/sampler This example shows the expected log output when SOFATracer is configured with a 20% sampling rate. The output includes details of requests made to the '/springmvc' endpoint. ```json json {"time":"2018-11-09 12:14:29.466","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173686946410159846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-5","baggage":""} {"time":"2018-11-09 12:15:21.776","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173692177410319846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-2","baggage":""} {"time":"2018-11-09 12:15:22.439","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173692243810359846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":1,"current.thread.name":"http-nio-8080-exec-6","baggage":""} {"time":"2018-11-09 12:15:22.817","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173692281510379846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-8","baggage":""} ``` -------------------------------- ### Datasource Client Digest Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-datasource Examine the datasource-client-digest.log file to view detailed tracing information for SQL operations, including trace ID, execution time, and SQL statement. ```json {"time":"2019-09-02 21:31:31.566","local.app":"SOFATracerDataSource","traceId":"0a0fe91d156743109138810017302","spanId":"0.1","span.kind":"client","result.code":"00","current.thread.name":"http-nio-8080-exec-1","time.cost.milliseconds":"15ms","database.name":"test","sql":"DROP TABLE IF EXISTS TEST;\nCREATE TABLE TEST(ID INT PRIMARY KEY%2C NAME VARCHAR(255));","connection.establish.span":"128ms","db.execute.cost":"15ms","database.type":"h2","database.endpoint":"jdbc:h2:~/test:-1","sys.baggage":"","biz.baggage":""} ``` -------------------------------- ### Implement Custom Sampler Rule Source: https://www.sofastack.tech/projects/sofa-tracer/sampler Implement the Sampler interface to define custom sampling logic. This example samples based on whether the span is from a server. ```java public class CustomOpenRulesSamplerRuler implements Sampler { private static final String TYPE = "CustomOpenRulesSamplerRuler"; @Override public SamplingStatus sample(SofaTracerSpan sofaTracerSpan) { SamplingStatus samplingStatus = new SamplingStatus(); Map tags = new HashMap(); tags.put(SofaTracerConstant.SAMPLER_TYPE_TAG_KEY, TYPE); tags = Collections.unmodifiableMap(tags); samplingStatus.setTags(tags); if (sofaTracerSpan.isServer()) { samplingStatus.setSampled(false); } else { samplingStatus.setSampled(true); } return samplingStatus; } @Override public String getType() { return TYPE; } @Override public void close() { // do nothing } } ``` -------------------------------- ### DataSource Statistics Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-datasource This JSON log entry summarizes SQL execution statistics over a period. It includes aggregated data such as execution count, total cost, success rate, and load test markers, keyed by application, database, and SQL statement. ```json {"time":"2019-09-02 21:31:50.435","stat.key":{"local.app":"SOFATracerDataSource","database.name":"test","sql":"DROP TABLE IF EXISTS TEST; CREATE TABLE TEST(ID INT PRIMARY KEY%2C NAME VARCHAR(255));"},"count":1,"total.cost.milliseconds":15,"success":"true","load.test":"F"} ``` -------------------------------- ### Get RestTemplate via Autowiring Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-resttemplate Obtain a RestTemplate instance through Spring's dependency injection mechanism. ```java @Autowired RestTemplate restTemplate; ``` -------------------------------- ### DataSource Digest Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-datasource This JSON log entry represents a single SQL statement execution trace. It includes details like timestamp, application name, trace IDs, span information, SQL statement, and execution times. ```json {"time":"2019-09-02 21:31:31.566","local.app":"SOFATracerDataSource","traceId":"0a0fe91d156743109138810017302","spanId":"0.1","span.kind":"client","result.code":"00","current.thread.name":"http-nio-8080-exec-1","time.cost.milliseconds":"15ms","database.name":"test","sql":"DROP TABLE IF EXISTS TEST; CREATE TABLE TEST(ID INT PRIMARY KEY%2C NAME VARCHAR(255));","connection.establish.span":"128ms","db.execute.cost":"15ms","database.type":"h2","database.endpoint":"jdbc:h2:~/test:-1","sys.baggage":"","biz.baggage":""} ``` -------------------------------- ### HttpClient Digest Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-httpclient This JSON log provides detailed information about an individual HttpClient request, including timestamps, trace IDs, request details, and response sizes. The application name can be configured when building the HttpClient instance. ```json {"time":"2019-09-02 23:43:13.191","local.app":"HttpClientDemo","traceId":"1e27a79c1567438993170100210107","spanId":"0","span.kind":"client","result.code":"200","current.thread.name":"I/O dispatcher 1","time.cost.milliseconds":"21ms","request.url":"http://localhost:8080/httpclient","method":"GET","req.size.bytes":0,"resp.size.bytes":-1,"remote.app":"","sys.baggage":"","biz.baggage":""} ``` -------------------------------- ### SOFARPC Client Statistics Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-sofarpc This JSON log entry provides aggregated statistics for RPC client calls. It includes the time, a unique stat key (method, app, service), call count, total duration, and success status. ```json {"time":"2018-05-18 07:02:19.717","stat.key":{"method":"method","local.app":"client","service":"app.service:1.0"},"count":10,"total.cost.milliseconds":17,"success":"Y"} ``` -------------------------------- ### HttpClient Statistics Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-httpclient This JSON log aggregates statistics for HttpClient requests over a specific time period. It includes the total count, total cost, success status, and load test flag, identified by a unique stat.key. ```json {"time":"2019-09-02 23:44:11.785","stat.key":{"method":"GET","local.app":"HttpClientDemo","request.url":"http://localhost:8080/httpclient"},"count":2,"total.cost.milliseconds":229,"success":"true","load.test":"F"} ``` -------------------------------- ### RestTemplate Statistical Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-resttemplate This JSON log provides aggregated statistical data for RestTemplate requests over a period. It summarizes request counts, total cost, success rates, and load test indicators. ```json {"time":"2019-09-03 10:34:04.130","stat.key":{"method":"GET","local.app":"RestTemplateDemo","request.url":"http://localhost:8801/asyncrest"},"count":1,"total.cost.milliseconds":5009,"success":"true","load.test":"F"} ``` -------------------------------- ### Propagate SOFATracer Context with Callable Source: https://www.sofastack.tech/projects/sofa-tracer/async For asynchronous tasks using `java.util.concurrent.Callable`, wrap your Callable with `SofaTracerCallable` to propagate SOFATracer context. This example demonstrates submitting a task to an `ExecutorService` and retrieving the result. ```java ExecutorService executor = Executors.newCachedThreadPool(); SofaTracerCallable sofaTracerSpanSofaTracerCallable = new SofaTracerCallable(new Callable() { @Override public Object call() throws Exception { return new Object(); } }); Future futureResult = executor.submit(sofaTracerSpanSofaTracerCallable); //do something in current thread Thread.sleep(1000); //another thread execute success and get result Object objectReturn = futureResult.get(); ``` -------------------------------- ### RestTemplate Digest Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-resttemplate This JSON log captures detailed request and response information for a RestTemplate call. It includes timing, trace IDs, request details, and baggage data. ```json {"time":"2019-09-03 10:33:10.336","local.app":"RestTemplateDemo","traceId":"0a0fe9271567477985327100211176","spanId":"0","span.kind":"client","result.code":"200","current.thread.name":"SimpleAsyncTaskExecutor-1","time.cost.milliseconds":"5009ms","request.url":"http://localhost:8801/asyncrest","method":"GET","req.size.bytes":0,"resp.size.bytes":0,"sys.baggage":"","biz.baggage":""} ``` -------------------------------- ### SOFARPC Client Digest Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-sofarpc This JSON log entry represents a client-side RPC call's trace data. It includes details like timestamp, trace ID, span ID, protocol, service, method, and performance metrics. ```json {"timestamp":"2018-05-20 17:03:20.708","tracerId":"1e27326d1526807000498100185597","spanId":"0","span.kind":"client","local.app":"SOFATracerRPC","protocol":"bolt","service":"com.alipay.sofa.tracer.examples.sofarpc.direct.DirectService:1.0","method":"sayDirect","current.thread.name":"main","invoke.type":"sync","router.record":"DIRECT","remote.app":"samples","remote.ip":"127.0.0.1:12200","local.client.ip":"127.0.0.1","result.code":"00","req.serialize.time":"33","resp.deserialize.time":"39","resp.size":"170","req.size":"582","client.conn.time":"0","client.elapse.time":"155","local.client.port":"59774","baggage":""} ``` -------------------------------- ### SOFARPC Server Digest Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-sofarpc This JSON log entry represents a server-side RPC request's trace data. It contains information such as timestamp, trace ID, span ID, service details, method, and server-specific performance metrics. ```json {"timestamp":"2018-05-20 17:00:53.312","tracerId":"1e27326d1526806853032100185011","spanId":"0","span.kind":"server","service":"com.alipay.sofa.tracer.examples.sofarpc.direct.DirectService:1.0","method":"sayDirect","remote.ip":"127.0.0.1","remote.app":"SOFATracerRPC","protocol":"bolt","local.app":"SOFATracerRPC","current.thread.name":"SOFA-BOLT-BIZ-12200-5-T1","result.code":"00","server.pool.wait.time":"3","biz.impl.time":"0","resp.serialize.time":"4","req.deserialize.time":"38","resp.size":"170","req.size":"582","baggage":""} ``` -------------------------------- ### Spring MVC Statistics Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-springmvc This JSON log entry provides aggregated statistics for a set of Spring MVC requests. It includes the time, a statistical key (combining app, URL, and method), request count, total cost, success status, and load test flag. ```json {"time":"2019-09-03 10:34:04.129","stat.key":{"method":"GET","local.app":"RestTemplateDemo","request.url":"http://localhost:8801/asyncrest"},"count":1,"total.cost.milliseconds":5006,"success":"true","load.test":"F"} ``` -------------------------------- ### Add SOFATracer Dependency Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-mvc Include the tracer-sofa-boot-starter dependency in your project's pom.xml to enable SOFATracer. ```xml com.alipay.sofa tracer-sofa-boot-starter ``` -------------------------------- ### Create Rest Service for Demo Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-datasource Implement a RestController to trigger SQL execution, allowing you to observe the generated tracer logs for SQL operations. ```java @RestController public class SimpleRestController { @Autowired private DataSource simpleDataSource; @RequestMapping("/create") public Map create() { Map resultMap = new HashMap(); try { Connection cn = simpleDataSource.getConnection(); Statement st = cn.createStatement(); st.execute("DROP TABLE IF EXISTS TEST; CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255));"); resultMap.put("success", true); resultMap.put("result", "CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); } catch (Throwable throwable) { resultMap.put("success", false); resultMap.put("error", throwable.getMessage()); } return resultMap; } } ``` -------------------------------- ### Configure Provider Application Properties Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-openfeign Set the application name, server port, and Zookeeper connection details for the provider. Enable Zookeeper discovery and set an instance ID. ```properties spring.application.name=tracer-provider server.port=8800 spring.cloud.zookeeper.connect-string=localhost:2181 spring.cloud.zookeeper.discovery.enabled=true spring.cloud.zookeeper.discovery.instance-id=tracer-provider ``` -------------------------------- ### Configure Consumer Application Properties Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-openfeign Set the application name, server port, and Zookeeper connection details for the consumer. Enable Zookeeper discovery and set an instance ID. ```properties spring.application.name=tracer-consumer server.port=8082 spring.cloud.zookeeper.connect-string=localhost:2181 spring.cloud.zookeeper.discovery.enabled=true spring.cloud.zookeeper.discovery.instance-id=tracer-consumer ``` -------------------------------- ### Reference Dubbo Service and Run Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-dubbo Reference the HelloService using the @Reference annotation and use ApplicationRunner to invoke the service. This demonstrates how the consumer interacts with the provider. ```java @Reference(async = false) public HelloService helloService; @Bean public ApplicationRunner runner() { return args -> { logger.info(helloService.SayHello("sofa")); }; } ``` -------------------------------- ### Introduce h2database and mysql-connector-java Dependencies Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-datasource Include h2database for in-memory testing and mysql-connector-java for database connectivity. ```xml com.h2database h2 runtime mysql mysql-connector-java ``` -------------------------------- ### Add SOFATracer and OpenFeign Dependencies to Provider Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-openfeign Include SOFATracer, Zookeeper discovery, and OpenFeign starters in the provider's pom.xml. SOFATracer version is managed by SOFABoot; manual specification might be needed for versions below 3.0.4. ```xml com.alipay.sofa tracer-sofa-boot-starter org.springframework.cloud spring-cloud-starter-zookeeper-discovery org.springframework.cloud spring-cloud-starter-openfeign ``` -------------------------------- ### Get Baggage Data from SpanContext Source: https://www.sofastack.tech/projects/sofa-tracer/utils Retrieve business (bizBaggage) and system (sysBaggage) data from the SpanContext. These are stored as maps. ```java SofaTracerSpanContext sofaTracerSpanContext = sofaTracerSpan.getSofaTracerSpanContext(); //获取 bizBaggage Map bizBaggages = sofaTracerSpanContext.getBizBaggage(); //获取 sysBaggage Map sysBaggages = sofaTracerSpanContext.getSysBaggage(); ``` -------------------------------- ### Get Logs from Span Source: https://www.sofastack.tech/projects/sofa-tracer/utils Retrieve log data associated with a Span. The logs are returned as a list of LogData objects. ```java List logDataList = sofaTracerSpan.getLogs(); ``` -------------------------------- ### Manual Datasource Configuration with SmartDataSource Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-datasource In non-Spring Boot environments or when using connection pools not automatically supported, manually configure SOFATracer by wrapping your data source with `com.alipay.sofa.tracer.plugins.datasource.SmartDataSource`. ```xml ... ... ``` -------------------------------- ### Get BaggageItem from Span Source: https://www.sofastack.tech/projects/sofa-tracer/utils Retrieve the value of a specific BaggageItem from the Span using its key. This operation accesses bizBaggage. ```java String baggageKey = "key"; String baggageValue = sofaTracerSpan.getBaggageItem(baggageKey); ``` -------------------------------- ### Enable Discovery Client and Feign Clients Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-openfeign Annotate the main application class with @SpringBootApplication, @RestController, @EnableDiscoveryClient, and @EnableFeignClients. Autowire the FeignService to make calls. ```java @SpringBootApplication @RestController @EnableDiscoveryClient @EnableFeignClients public class FeignClientApplication { public static void main(String[] args) { SpringApplication.run(FeignClientApplication.class,args); } @Autowired private FeignService feignService; @RequestMapping public String test(){ return feignService.testFeign(); } } ``` -------------------------------- ### Implement and Publish Dubbo Service Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-dubbo Implement the HelloService interface and use the @Service annotation to publish it as a Dubbo service. This makes the service available for consumers. ```java @Service public class HelloServiceImpl implements HelloService { @Override public String SayHello(String name) { return "Hello , "+name; } } ``` -------------------------------- ### Get Tags from Span Source: https://www.sofastack.tech/projects/sofa-tracer/utils Retrieve tags associated with a Span. SOFATracer categorizes tags into string, boolean, and number types. ```java Map tagsStr = sofaTracerSpan.getTagsWithStr(); Map tagsBool = sofaTracerSpan.getTagsWithBool(); Map tagsNumber = sofaTracerSpan.getTagsWithNumber(); ``` -------------------------------- ### Add SOFATracer and OkHttp Dependencies Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-okhttp Include SOFATracer and OkHttp dependencies in your project's pom.xml. Ensure you are using compatible versions. ```xml com.alipay.sofa tracer-sofa-boot-starter com.squareup.okhttp3 okhttp 3.12.1 ``` -------------------------------- ### Get SOFATracer Context Source: https://www.sofastack.tech/projects/sofa-tracer/utils Retrieve the current SOFATracer context, which is cached in ThreadLocal. This context allows for operations on cached Spans. ```java SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); ``` -------------------------------- ### Get TraceId and SpanId from Span Source: https://www.sofastack.tech/projects/sofa-tracer/utils Extract the TraceId and SpanId from a Span's context. Ensure the Span is not null before attempting to retrieve its context. ```java SofaTracerSpanContext sofaTracerSpanContext = currentSpan.getSofaTracerSpanContext(); String traceId = sofaTracerSpanContext.getTraceId(); String spanId = sofaTracerSpanContext.getSpanId(); ``` -------------------------------- ### Get Current Span from Context Source: https://www.sofastack.tech/projects/sofa-tracer/utils Obtain the current Span from the SOFATracer context. This is useful for application developers who need to access Span information. ```java SofaTracerSpan sofaTracerSpan = sofaTraceContext.getCurrentSpan(); ``` -------------------------------- ### Configure SOFATracer Properties Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-resttemplate Set the application name and logging path in application.properties for SOFATracer. ```properties # Application Name spring.application.name=TestTemplateDemo # logging path logging.path=./logs ``` -------------------------------- ### Logback Implementation Dependency for Spring Boot Source: https://www.sofastack.tech/projects/sofa-tracer/print-traceid-spanid Add the Spring Boot starter for logging if you are using Logback as your logging implementation within a Spring Boot application. ```xml org.springframework.boot spring-boot-starter-logging ``` -------------------------------- ### Log4j2 Implementation Dependency for Spring Boot Source: https://www.sofastack.tech/projects/sofa-tracer/print-traceid-spanid Include the Spring Boot starter for Log4j2 if you choose Log4j2 as your logging implementation. Note that SOFABoot does not manage the Log4j2 version. ```xml org.springframework.boot spring-boot-starter-log4j2 1.4.2.RELEASE ``` -------------------------------- ### Configure Custom Sampler in application.properties Source: https://www.sofastack.tech/projects/sofa-tracer/sampler Configure your custom sampler by specifying its class name in the application.properties file. This tells SOFATracer which custom rule to use. ```properties com.alipay.sofa.tracer.samplerName.samplerCustomRuleClassName=com.alipay.sofa.tracer.examples.springmvc.sampler.CustomOpenRulesSamplerRuler ``` -------------------------------- ### Configure Optional Application Settings Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-datasource Configure logging path and h2database console properties for easier debugging and log viewing. These are optional for SOFATracer integration but useful for the demo. ```properties # logging path logging.path=./logs # h2 web consloe 路径 spring.h2.console.path=/h2-console # 开启 h2 web consloe,默认为 false spring.h2.console.enabled=true #允许远程访问 h2 web consloe spring.h2.console.settings.web-allow-others=true spring.datasource.username=sofa spring.datasource.password=123456 spring.datasource.url=jdbc:h2:~/test spring.datasource.driver-class-name=org.h2.Driver ``` -------------------------------- ### Logback Pattern Configuration for TraceId and SpanId Source: https://www.sofastack.tech/projects/sofa-tracer/print-traceid-spanid Configure the Logback pattern layout to include SOFATracer's TraceId and SpanId by referencing them from the MDC using %X{SOFA-TraceId} and %X{SOFA-SpanId}. If these values are not present, they will appear as empty strings. ```xml %d{yyyy-MM-dd HH:mm:ss.SSS} %5p [%X{SOFA-TraceId}, %X{SOFA-SpanId}] ---- %m%n ``` -------------------------------- ### Configure SOFATracer Application Properties Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-okhttp Set the application name and logging path in application.properties for SOFATracer. The application name is used for tracing identification. ```properties # Application Name spring.application.name=OkHttpClientDemo # logging path logging.path=./logs # port server.port=8081 ``` -------------------------------- ### Introduce Connection Pool Dependencies Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-datasource Add dependencies for your chosen database connection pool, such as Druid, c3p0, Tomcat JDBC, DBCP, or HikariCP. ```xml com.alibaba druid 1.0.12 c3p0 c3p0 0.9.1.1 org.apache.tomcat tomcat-jdbc 8.5.31 commons-dbcp commons-dbcp 1.4 com.zaxxer HikariCP-java6 2.3.8 ``` -------------------------------- ### Spring MVC Digest Log Example Source: https://www.sofastack.tech/projects/sofa-tracer/log-format-springmvc This JSON log entry represents a single traced request in Spring MVC. It includes details like timestamp, application name, trace ID, span ID, request URL, method, and response status. ```json {"time":"2019-09-03 10:33:10.336","local.app":"RestTemplateDemo","traceId":"0a0fe9271567477985327100211176","spanId":"0.1","span.kind":"server","result.code":"200","current.thread.name":"http-nio-8801-exec-2","time.cost.milliseconds":"5006ms","request.url":"http://localhost:8801/asyncrest","method":"GET","req.size.bytes":-1,"resp.size.bytes":0,"sys.baggage":"","biz.baggage":""} ``` -------------------------------- ### Build Asynchronous RestTemplate Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-resttemplate Construct an AsyncRestTemplate instance using SofaTracerRestTemplateBuilder for asynchronous calls. ```java AsyncRestTemplate asyncRestTemplate = SofaTracerRestTemplateBuilder .buildAsyncRestTemplate(); ListenableFuture> forEntity = asyncRestTemplate.getForEntity( "http://sac.alipay.net:8080/asyncrest", String.class); ``` -------------------------------- ### Define HelloService Interface Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-dubbo Define the service interface that will be used for communication between Dubbo provider and consumer. This interface specifies the methods available for remote invocation. ```java public interface HelloService { String SayHello(String name); } ``` -------------------------------- ### Configure SOFATracer Properties Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-mvc Set the spring.application.name and logging.path in application.properties for SOFATracer configuration. ```properties # Application Name spring.application.name=SOFATracerSpringMVC # logging path logging.path=./logs ``` -------------------------------- ### SOFATracer Sampling: Probabilistic Rate (20%) Source: https://www.sofastack.tech/projects/sofa-tracer/sampler When the sampling rate is set between 0 and 100 (e.g., 20%), logs are printed probabilistically. This allows for capturing a subset of traces for performance monitoring. ```json {"time":"2018-11-09 12:14:29.466","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173686946410159846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-5","baggage":""} {"time":"2018-11-09 12:15:21.776","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173692177410319846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-2","baggage":""} ``` -------------------------------- ### Configure Dubbo Consumer for SOFATracer Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-dubbo Configure the Dubbo consumer's application.properties to enable SOFATracer integration. This includes setting the application name, registry address, and consumer filter. ```properties spring.application.name=dubbo-consumer dubbo.registry.address=zookeeper://localhost:2181 dubbo.consumer.filter=dubboSofaTracerFilter logging.path=./logs ``` -------------------------------- ### Build Synchronous RestTemplate Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-resttemplate Construct a RestTemplate instance using SofaTracerRestTemplateBuilder for synchronous calls. ```java RestTemplate restTemplate = SofaTracerRestTemplateBuilder.buildRestTemplate(); ResponseEntity responseEntity = restTemplate.getForEntity( "http://sac.alipay.net:8080/rest", String.class); ``` -------------------------------- ### SLF4J Logger Initialization Source: https://www.sofastack.tech/projects/sofa-tracer/print-traceid-spanid Initialize an SLF4J logger instance in your application code. This is necessary for logging messages and utilizing MDC features. ```java //引入接口 import org.slf4j.Logger; import org.slf4j.LoggerFactory; //构造日志打印实例 private static final Logger logger = LoggerFactory.getLogger(XXX.class); ``` -------------------------------- ### Create a RESTful Controller Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-resttemplate Define a Spring RestController with endpoints for RESTful services. ```java @RestController public class SampleController { private final AtomicLong counter = new AtomicLong(0); @RequestMapping("/rest") public Map rest() { Map map = new HashMap(); map.put("count", counter.incrementAndGet()); return map; } @RequestMapping("/asyncrest") public Map asyncrest() throws InterruptedException { Map map = new HashMap(); map.put("count", counter.incrementAndGet()); Thread.sleep(5000); return map; } } ``` -------------------------------- ### Create a RESTful Controller Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-mvc Implement a simple REST controller in your Spring MVC application to handle requests. ```java @RestController public class SampleRestController { private static final String TEMPLATE = "Hello, %s!"; private final AtomicLong counter = new AtomicLong(); /** * http://localhost:8080/springmvc * @param name name * @return map */ @RequestMapping("/springmvc") public Map springmvc(@RequestParam(value = "name", defaultValue = "SOFATracer SpringMVC DEMO") String name) { Map resultMap = new HashMap(); resultMap.put("success", true); resultMap.put("id", counter.incrementAndGet()); resultMap.put("content", String.format(TEMPLATE, name)); return resultMap; } } ``` -------------------------------- ### Configure Application Name Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-datasource Set the spring.application.name property in your application configuration. SOFATracer requires this to be set, similar to SOFABoot's requirements. ```properties spring.application.name=SOFATracerDataSource ``` -------------------------------- ### SOFATracer Sampling: Rate 0% Source: https://www.sofastack.tech/projects/sofa-tracer/sampler When the sampling rate is set to 0, no summary logs will be printed. This is useful for disabling tracing entirely. ```text No spring-mvc-digest.log file is generated in the ./logs/tracerlog/ directory. ``` -------------------------------- ### Configure Dubbo Provider for SOFATracer Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-dubbo Configure the Dubbo provider's application.properties to enable SOFATracer integration. This includes setting the application name, Dubbo scan packages, provider filter, protocol, and registry address. ```properties spring.application.name=dubbo-provider dubbo.scan.base-packages=com.alipay.sofa.tracer.examples.dubbo.impl dubbo.provider.filter=dubboSofaTracerFilter dubbo.protocol.name=dubbo dubbo.registry.address=zookeeper://localhost:2181 logging.path=./logs ``` -------------------------------- ### SOFATracer Log File Structure Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-mvc Overview of the log file structure generated by SOFATracer in the configured log directory. ```file-structure ./logs ├── spring.log └── tracelog ├── spring-mvc-digest.log ├── spring-mvc-stat.log ├── static-info.log └── tracer-self.log ``` -------------------------------- ### Provider REST Controller Source: https://www.sofastack.tech/projects/sofa-tracer/usage-of-openfeign A simple REST controller for the provider that returns a string response. This endpoint will be called by the OpenFeign consumer. ```java @RestController public class UserController { @RequestMapping("/feign") public String testFeign(HttpServletRequest request) { return "hello tracer feign"; } } ```