OpenTelemetry Go Auto Instrumentation

414
下载
opentelemetry-go-auto-instrumentation 是阿里巴巴开源的基于OpenTelemetry规范的Golang应用无侵入编译时注入监控方案,可以在用户完全不修改业务代码的情况下对用户的Golang应用进行监控。

如何在日志中注入traceID


如何在日志中注入traceID

自动注入

如果我们使用 opentelemetry-go-auto-instrumentation 所支持的日志框架,如图所示。TraceId 和 SpanId 会自动注入日志。

Terminal window
package main
import (
"go.uber.org/zap"
"net/http"
)
func main() {
http.HandleFunc("/log", func(w http.ResponseWriter, r *http.Request) {
logger := zap.NewExample()
logger.Debug("this is debug message")
logger.Info("this is info message")
logger.Warn("this is warn message")
logger.Error("this is error message")
})
http.ListenAndServe(":9999", nil)
}

例如,如果我们用 opentelemetry-go-auto-instrumentation 生成下面的 Go 文件,运行二进制文件并访问 localhost:9999/log,就会看到下面的输出:

Terminal window
{"level":"debug","msg":"this is debug message","trace_id":"d62a8fea286cc66de9c68ca17d4faa88","span_id":"7cb6d692769ffd32"}
{"level":"info","msg":"this is info message","trace_id":"d62a8fea286cc66de9c68ca17d4faa88","span_id":"7cb6d692769ffd32"}
{"level":"warn","msg":"this is warn message","trace_id":"d62a8fea286cc66de9c68ca17d4faa88","span_id":"7cb6d692769ffd32"}
{"level":"error","msg":"this is error message","trace_id":"d62a8fea286cc66de9c68ca17d4faa88","span_id":"7cb6d692769ffd32"}
{"level":"debug","msg":"this is debug message","trace_id":"e56a6f1e7ed7af48cce8f64d045ed158","span_id":"def0b8cf10fe8844"}
{"level":"info","msg":"this is info message","trace_id":"e56a6f1e7ed7af48cce8f64d045ed158","span_id":"def0b8cf10fe8844"}
{"level":"warn","msg":"this is warn message","trace_id":"e56a6f1e7ed7af48cce8f64d045ed158","span_id":"def0b8cf10fe8844"}
{"level":"error","msg":"this is error message","trace_id":"e56a6f1e7ed7af48cce8f64d045ed158","span_id":"def0b8cf10fe8844"}

TraceId和SpanId会被自动注入到日志中。

手动注入

如果框架不支持 opentelemetry-go-auto-instrumentation。我们可以手动将 TraceId 和 SpanId 注入日志:

Terminal window
package main
import (
"go.opentelemetry.io/otel/sdk/trace"
"go.uber.org/zap"
"net/http"
)
func main() {
http.HandleFunc("/logwithtrace", func(w http.ResponseWriter, r *http.Request) {
logger := zap.NewExample()
traceId, spanId := trace.GetTraceAndSpanId()
logger.Info("this is info message with fileds",
zap.String("traceId", traceId),
zap.String("spanId", spanId),
)
})
http.ListenAndServe(":9999", nil)
}

例如,如果我们用 opentelemetry-go-auto-instrumentation 编译上面的 Go 文件,运行二进制文件,然后 curl localhost:9999/logwithtrace,就会看到下面的输出:

Terminal window
{"level":"info","msg":"this is info message with fileds","traceId":"92d63797010a2040484222a74c5ce304","spanId":"5a2c84c807a6e12c"}

上面的代码被放在示例目录中。


observability.cn Authors 2024 | Documentation Distributed under CC-BY-4.0
Copyright © 2017-2024, Alibaba. All rights reserved. Alibaba has registered trademarks and uses trademarks.
浙ICP备2021005855号-32