一.golang应用程序
该golang应用监听8080端口,在http handler中又对www.baidu.com或www.163.com发起了调用:
package main
import (
"fmt"
"io"
"log"
"math/rand"
"net/http"
"time"
)
func handleRequest(rw http.ResponseWriter, _ *http.Request) {
time.Sleep(time.Duration(rand.Float64()*400.0) * time.Millisecond)
if rand.Int31n(100) < 80 {
http.Get("http://www.baidu.com")
rw.WriteHeader(200)
if _, err := io.WriteString(rw, "Hello from the example HTTP service.\n"); err != nil {
log.Fatal(err)
}
} else {
http.Get("http://www.163.com")
rw.WriteHeader(500)
if _, err := io.WriteString(rw, "Simulating an error response with HTTP status 500.\n"); err != nil {
log.Fatal(err)
}
}
}
func main() {
fmt.Println("Listening on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", http.HandlerFunc(handleRequest)))
}
二. 启动beyla
这里重点配置BEYLA_PRINT_TRACES=true,在terminal上打印trace信息:
BEYLA_PROMETHEUS_PORT=9400 BEYLA_OPEN_PORT=8080 BEYLA_PRINT_TRACES=true BEYLA_LOG_LEVEL=DEBUG bin/beyla
三. 发起HTTP调用
# curl localhost:8080/
Hello from the example HTTP service.
四. 查看beyla的trace打印
2024-02-04 04:21:37.13142137 (38.384446ms[38.384446ms]) 200 GET []->[www.baidu.com:0] size:0B svc=[example-http-service go] traceparent=[00-9201c25ae90fee19c5bb224e5b1d4941-4228643b4d469989-01]
2024-02-04 04:21:36.13142136 (214.410762ms[214.101219ms]) 200 GET / [127.0.0.1]->[localhost:8080] size:0B svc=[example-http-service go] traceparent=[00-9201c25ae90fee19c5bb224e5b1d4941-0000000000000000-01]
上述打印中,traceparent的格式=00-traceId-parentId-type
可以看出,一个http调用:
- 产生了一个trace信息,traceId=9201c25ae90fee19c5bb224e5b1d4941;
产生了两个span信息:
- span2.parentSpanId=0000000000000000,由于parentSpanId=0,它是用户发起的http调用的span;
- span1.parentSpanId=4228643b4d469989,即发起www.baidu.com调用的span;
也就是说,http调用的trace信息都采集到了,那么trace context propagation呢?
可以抓包看一下,重点看发起GET www.baidu.com的HTTP包:
GET / HTTP/1.1^M
Host: www.baidu.com^M
User-Agent: Go-http-client/1.1^M
Traceparent: 00-9201c25ae90fee19c5bb224e5b1d4941-9cbf834b6561a2d3-01^M
Accept-Encoding: gzip
可以看出,golang程序对外发起GET调用时,http header中增加了traceparent字段,而接收GET调用的外部服务,可以根据header中的traceparent字段,了解trace上下文信息(traceId/parentId),即实现trace context propagation。
参考:
1.https://github.com/grafana/beyla/issues/521
2.https://github.com/lwangrabbit/beyla/blob/main/docs/sources/distributed-traces.md
3.https://www.yuque.com/cnych/otel/liux4yh24wiqt121
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。