使用opentelemetry开源标准协议实现:
搭建trace、metric、log三种观测信号的服务端
通过opentelemetry提供的SDK库封装业务侧操作
通过切面编程的方式获取业务服务相关信息
建立跟服务端的通信,发送信息到服务端
下面简单聊聊第二点的实现
启动Exporter
exporter, err := otlptracehttp.New(context.Background(), otlpTraceOpts...)
if err != nil {
return nil, err
}
// New constructs a new Exporter and starts it.
func New(ctx context.Context, client Client) (*Exporter, error) {
exp := NewUnstarted(client)
if err := exp.Start(ctx); err != nil {
return nil, err
}
return exp, nil
}
exporter支持两种方式的通信:http和grpc。
以http为例,这里其实就是构造一个跟opentelemetry服务端通信的client实例
注:这里根据需要可以启动多个exporter:trace、metric、log
Span处理器
自定义一个span处理器,比如实现如下特性:
-
该处理器通过一个span的队列channel,来对请求过程中的span进行处理,
启动一个协程:该程序是一个loop轮训,从队列里面获取span,进行相关逻辑处理,通过exporter上传span信息给opentelemetry服务器,实现opentelemetry接口
需要实现opentelemetry的onEnd接口,获取请求过程中的span
// OnEnd method enqueues a ReadOnlySpan for later processing.func (bsp *batchSpanProcessor) OnEnd(s sdktrace.ReadOnlySpan) {
// Do not enqueue spans if we are just going to drop them.
if bsp.e == nil {
return
}
bsp.enqueue(s)
}
-
上报span信息
调用exporter接口:
// ExportSpans exports a batch of spans.
//
// This function is called synchronously, so there is no concurrency
// safety requirement. However, due to the synchronous calling pattern,
// it is critical that all timeouts and cancellations contained in the
// passed context must be honored.
//
// Any retry logic must be contained in this function. The SDK that
// calls this function will not implement any retry logic. All errors
// returned by this function are considered unrecoverable and will be
// reported to a configured error Handler.
ExportSpans(ctx context.Context, spans []ReadOnlySpan) error
Log处理器
通过在请求的切面点处,获取到的相关信息,通过opentelemetry的log exporter发送日志给opentelemetry服务器
https://juejin.cn/post/7172540307794296862