examples_test.go 2.15 KB
Newer Older
1 2 3
package tracing_test

import (
4
	"context"
5 6 7
	"fmt"
	"io"
	"net/http"
8
	"os/exec"
9 10
	"time"

11
	log "github.com/sirupsen/logrus"
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
	"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()
				io.Copy(w, resp.Body)
			}),
			// 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))
}
69 70 71 72 73 74 75 76 77 78 79 80 81

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 {
82
		log.WithError(err).Fatal("Command failed")
83 84 85 86 87 88 89 90 91 92 93 94 95
	}
}

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)
}