Skip to content

Commit

Permalink
logging: populate entry trace from HTTP request header
Browse files Browse the repository at this point in the history
If we see the X-Cloud-Trace-Context header and the user hasn't already
set the trace field, populate the trace field with the header.

See #448.

Change-Id: I4870616d6ff5e94ea3af94ff2fb5a8b346335766
Reviewed-on: https://code-review.googlesource.com/30890
Reviewed-by: kokoro <noreply+kokoro@google.com>
Reviewed-by: Jean de Klerk <deklerk@google.com>
  • Loading branch information
jba committed Jul 26, 2018
1 parent d4056dd commit 7f7e4d3
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
3 changes: 3 additions & 0 deletions logging/logging.go
Expand Up @@ -794,6 +794,9 @@ func toLogEntry(e Entry) (*logpb.LogEntry, error) {
if err != nil {
return nil, err
}
if e.Trace == "" && e.HTTPRequest != nil && e.HTTPRequest.Request != nil {
e.Trace = e.HTTPRequest.Request.Header.Get("X-Cloud-Trace-Context")
}
ent := &logpb.LogEntry{
Timestamp: ts,
Severity: logtypepb.LogSeverity(e.Severity),
Expand Down
52 changes: 52 additions & 0 deletions logging/logging_unexported_test.go
Expand Up @@ -227,6 +227,58 @@ func TestToLogEntryPayload(t *testing.T) {
}
}

func TestToLogEntryTrace(t *testing.T) {
// Verify that we get the trace from the HTTP request if it isn't
// provided by the caller.
u := &url.URL{Scheme: "http"}
for _, test := range []struct {
in Entry
want string
}{
{Entry{}, ""},
{Entry{Trace: "t1"}, "t1"},
{
Entry{
HTTPRequest: &HTTPRequest{
Request: &http.Request{URL: u, Header: http.Header{"foo": {"bar"}}},
},
},
"",
},
{
Entry{
HTTPRequest: &HTTPRequest{
Request: &http.Request{
URL: u,
Header: http.Header{"X-Cloud-Trace-Context": {"t2"}},
},
},
},
"t2",
},
{
Entry{
HTTPRequest: &HTTPRequest{
Request: &http.Request{
URL: u,
Header: http.Header{"X-Cloud-Trace-Context": {"t3"}},
},
},
Trace: "t4",
},
"t4",
},
} {
e, err := toLogEntry(test.in)
if err != nil {
t.Fatalf("%+v: %v", test.in, err)
}
if got := e.Trace; got != test.want {
t.Errorf("got %q, want %q", got, test.want)
}
}
}

func TestFromHTTPRequest(t *testing.T) {
const testURL = "http:://example.com/path?q=1"
u, err := url.Parse(testURL)
Expand Down

0 comments on commit 7f7e4d3

Please sign in to comment.