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