gitlab.com/gitlab-org/labkit@v1.21.0/tracing/examples_test.go (about) 1 package tracing_test 2 3 import ( 4 "context" 5 "fmt" 6 "io" 7 "net/http" 8 "os/exec" 9 "time" 10 11 log "github.com/sirupsen/logrus" 12 "gitlab.com/gitlab-org/labkit/tracing" 13 ) 14 15 // This example shows how to initialize tracing 16 // and then wrap all incoming calls. 17 func Example() { 18 // Tell the tracer to initialize as service "gitlab-wombat" 19 tracing.Initialize(tracing.WithServiceName("gitlab-wombat")) 20 21 tr := &http.Transport{ 22 MaxIdleConns: 10, 23 IdleConnTimeout: 30 * time.Second, 24 DisableCompression: true, 25 } 26 27 client := &http.Client{ 28 Transport: tracing.NewRoundTripper(tr), 29 } 30 31 // Listen and propagate traces 32 http.Handle("/foo", 33 // Add the tracing middleware in 34 tracing.Handler( 35 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 36 req, err := http.NewRequest(http.MethodGet, "http://localhost:8080/bar", nil) 37 if err != nil { 38 w.WriteHeader(500) 39 return 40 } 41 42 req = req.WithContext(r.Context()) 43 44 resp, err := client.Do(req) 45 if err != nil { 46 w.WriteHeader(500) 47 return 48 } 49 defer resp.Body.Close() 50 51 _, err = io.Copy(w, resp.Body) 52 if err != nil { 53 w.WriteHeader(500) 54 return 55 } 56 }), 57 // Use this route identifier with the tracing middleware 58 tracing.WithRouteIdentifier("/foo"), 59 )) 60 61 // Listen and propagate traces 62 http.Handle("/bar", 63 // Add the tracing middleware in 64 tracing.Handler( 65 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 66 fmt.Fprintf(w, "bar") 67 }), 68 // Use this route identifier with the tracing middleware 69 tracing.WithRouteIdentifier("/bar"), 70 )) 71 72 log.Fatal(http.ListenAndServe(":0", nil)) 73 } 74 75 func ExampleNewEnvInjector() { 76 envInjector := tracing.NewEnvInjector() 77 78 cmd := exec.Command("ls") 79 env := []string{ 80 "FOO=bar", 81 } 82 83 // envInjector will inject any required values 84 cmd.Env = envInjector(context.Background(), env) 85 86 if err := cmd.Run(); err != nil { 87 log.WithError(err).Fatal("Command failed") 88 } 89 } 90 91 func ExampleExtractFromEnv() { 92 // Tell the tracer to initialize as service "gitlab-child-process" 93 tracing.Initialize(tracing.WithServiceName("gitlab-child-process")) 94 95 ctx, finished := tracing.ExtractFromEnv(context.Background()) 96 defer finished() 97 98 // Program execution happens here... 99 func(_ context.Context) {}(ctx) 100 }