如果按照我前两节错误处理、日志收集配置的话,我们通过日志中的traceId也可以完整看到报错时候的整体链路日志,但是不报错的时候或者想方便的查看单个业务整个链路调用的执行时间是不太方便查看的,所以最好还是加上链路追踪。
go-zero底层已经帮我们把代码跟链路追踪对接的代码已经写好了
func startAgent(c Config) error {opts := []sdktrace.TracerProviderOption{// Set the sampling rate based on the parent span to 100%sdktrace.WithSampler(sdktrace.Parentbased(sdktrace.TraceIDRatiobased(c.Sampler))),// Record information about this application in an Resource.sdktrace.WithResource(resource.NewSchemaless(semconv.ServiceNameKey.String(c.Name))),}if len(c.Endpoint) > 0 {exp, err := createExporter(c)if err != nil {logx.Error(err)return err}// Always be sure to batch in production.opts = append(opts, sdktrace.WithBatcher(exp))}tp := sdktrace.NewTracerProvider(opts...)otel.SetTracerProvider(tp)otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))otel.SetErrorHandler(otel.ErrorHandlerFunc(func(err error) {logx.Errorf("[otel] error: %v", err)}))return nil}
默认支持jaeger、zinpink
package trace// TraceName represents the tracing name.const TraceName = "go-zero"// A Config is a opentelemetry config.type Config struct {Name string `json:",optional"`Endpoint string `json:",optional"`Sampler float64 `json:",default=1.0"`Batcher string `json:",default=jaeger,options=jaeger|zipkin"`}
我们只需要在我们的业务代码配置中,也就是你的业务配置的yaml中配置参数即可。
2、实现go-zero-looklook是以jaeger来实现的
2.1 jaeger项目的docker-compose-env.yaml中配置了jaeger
services: #jaeger链路追踪 jaeger: image: jaegertracing/all-in-one:latest container_name: jaeger ports: - "5775:5775/udp" - "6831:6831/udp" - "6832:6832/udp" - "5778:5778" - "16686:16686" - "14268:14268" - "9411:9411" environment: - SPAN_STORAGE_TYPE=elasticsearch - ES_SERVER_URLS=http://elasticsearch:9200 - LOG_LEVEL=debug networks: - looklook_net ........
其中jager_collector 依赖elasticsearch做存储,所以要把elasticsearch安装上,前一节收集日志时候我们已经演示了。
2.2 业务配置我们以用户服务为例
1)api配置
app/usercenter/cmd/api/etc/usercenter.yaml
Name: usercenter-apiHost: 0.0.0.0Port: 8002Mode: dev......#链路追踪Telemetry: Name: usercenter-api Endpoint: http://jaeger:14268/api/traces Sampler: 1.0 Batcher: jaeger
2)rpc配置
Name: usercenter-rpcListenOn: 0.0.0.0:9002Mode: dev.....#链路追踪Telemetry: Name: usercenter-rpc Endpoint: http://jaeger:14268/api/traces Sampler: 1.0 Batcher: jaeger
2.3 查看链路请求用户服务注册、登陆、获取登陆用户信息
浏览器输入 http://127.0.0.1:16686/search即可查看
3、结尾日志、链路追踪我们都整理完了,好的系统一定能及时监控异常,接下来要看服务监控了。