Introducing HTTP Tracing

Introduction

In Go 1.7 we introduced HTTP tracing, a facility to gather fine-grained information throughout the lifecycle of an HTTP client request. Support for HTTP tracing is provided by the net/http/httptrace package. The collected information can be used for debugging latency issues, service monitoring, writing adaptive systems, and more.

HTTP events

The httptrace package provides a number of hooks to gather information during an HTTP round trip about a variety of events. These events include:

  • Connection creation
  • Connection reuse
  • DNS lookups
  • Writing the request to the wire
  • Reading the response

Tracing events

You can enable HTTP tracing by putting an *httptrace.ClientTrace containing hook functions into a request’scontext.Context. Various http.RoundTripper implementations report the internal events by looking for context’s *httptrace.ClientTrace and calling the relevant hook functions.

The tracing is scoped to the request’s context and users should put a *httptrace.ClientTrace to the request context before they start a request.

    req, _ := http.NewRequest("GET", "http://example.com", nil)
    trace := &httptrace.ClientTrace{
        DNSDone: func(dnsInfo httptrace.DNSDoneInfo) {
            fmt.Printf("DNS Info: %+v\n", dnsInfo)
        },
        GotConn: func(connInfo httptrace.GotConnInfo) {
            fmt.Printf("Got Conn: %+v\n", connInfo)
        },
    }
    req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
    if _, err := http.DefaultTransport.RoundTrip(req); err != nil {
        log.Fatal(err)
    }

During a round trip, http.DefaultTransport will invoke each hook as an event happens. The program above will print the DNS information as soon as the DNS lookup is complete. It will similarly print connection information when a connection is established to the request’s host.

https://blog.golang.org/http-tracing

Advertisements