使用zipkin-go进行完整跟踪

时间:2019-08-29 06:03:05

标签: go zipkin distributed-tracing

我有一些服务。我想使用zipkin-go跟踪这些服务。在每项服务中,我都在调用其他一些内部服务或数据库调用。我想跟踪每个活动,例如调用内部服务或数据库所花费的时间。我已经使用互联网上的可用教程来实现。下面是我的代码:

package main

import (
"fmt"
"os"
"net/http"
"log"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"Upload-Image-API/services/controllers/updatemodrefid"
"Upload-Image-API/services/controllers/uploadimage"
"Upload-Image-API/services/utils"
"github.com/openzipkin/zipkin-go"
"github.com/openzipkin/zipkin-go/model"
zipkinhttp "github.com/openzipkin/zipkin-go/middleware/http"
reporterhttp "github.com/openzipkin/zipkin-go/reporter/http"
)

const endpointURL = "http://localhost:9411/api/v2/spans"

func newTracer() (*zipkin.Tracer, error) {
   // The reporter sends traces to zipkin server
   reporter := reporterhttp.NewReporter(endpointURL)
   port := utils.GetString("serviceListeningPort")
   if port == "" {
        fmt.Println("Port is not defined in configuration ...!!!")
        os.Exit(1)
   }
   // Local endpoint represent the local service information
   localEndpoint := &model.Endpoint{ServiceName: "Upload-Image-API", Port: 7795}

   // Sampler tells you which traces are going to be sampled or not. In this case we will record 100% (1.00) of traces.
   sampler, err := zipkin.NewCountingSampler(1)
   if err != nil {
      return nil, err
   }

   t, err := zipkin.NewTracer(
      reporter,
      zipkin.WithSampler(sampler),
      zipkin.WithLocalEndpoint(localEndpoint),
   )
   if err != nil {
      return nil, err
   }

   return t, err
}


func main() {
    var err error
    var environment = os.Args[1]
    err = utils.LoadDefaultConfig(environment)
    tracer, err := newTracer()
    if err != nil {
      log.Fatal(err)
    }
    // We add the instrumented transport to the defaultClient
    // that comes with the zipkin-go library
    http.DefaultClient.Transport, err = zipkinhttp.NewTransport(
        tracer,
        zipkinhttp.TransportTrace(true),
    )
    if err != nil {
      log.Fatal(err)
    }
    if err != nil {
        fmt.Println("Could not load the configuration because of following err " + err.Error() + " ...!!!")
        os.Exit(1)
    } else {
        fmt.Println("Configurations sucessfully loaded for environment " + environment + " ...!!!")
    }
    allowedHeaders := handlers.AllowedHeaders([]string{"X-Requested-With"})
    allowedOrigins := handlers.AllowedOrigins([]string{"*"})
    allowedMethods := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"})

    port := utils.GetString("serviceListeningPort")
    if port == "" {
        fmt.Println("Port is not defined in configuration ...!!!")
        os.Exit(1)
    }
    router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/uploadimage", uploadimage.UploadImages).Methods("POST", "GET")
    router.HandleFunc("/updatemodrefid", updatemodrefid.UpdateModRefId).Methods("POST", "GET")
    router.Use(zipkinhttp.NewServerMiddleware(
  tracer,
  zipkinhttp.SpanName("request")), // name for request span
)
    err = http.ListenAndServe(port, handlers.CORS(allowedHeaders, allowedOrigins, allowedMethods)(router))
    if err != nil {
        fmt.Println("Count not start the server because of following err " + err.Error())
        return
    }
}

我正在跟踪我的请求,但是我无法跟踪uploadimage控制器内部发生的情况。以下是我的zipkin用户界面的屏幕截图:

Zipkin UI

我想跟踪uploadimage控制器内部发生的所有活动。我需要通过什么才能跟踪所有内容。

1 个答案:

答案 0 :(得分:0)

我是zipkin和golang的新手,如果要跟踪内部过程,则可以根据上下文创建跨度

示例:假设您有一个名为Login的api,在登录名内您可能会执行数据库操作或任何其他操作

func Login(res http.ResponseWriter, req *http.Request) {
    span, _ := tracer.StartSpanFromContext(req.Context(), "database")
    databaseOperation()
    span.Finish()
}