Debian Codegraph @

server/requestlog/stackdriver_test.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package requestlog
16
17 import (
18 "bytes"
19 "context"
20 "encoding/json"
21 "fmt"
22 "io"
23 "net/http"
24 "net/http/httptest"
25 "strings"
26 "testing"
27 "time"
28
29 "go.opentelemetry.io/otel"
30 "go.opentelemetry.io/otel/trace"
31 )
32
33 func TestStackdriverLog(t *testing.T) {
34 const (
35 startTime = 1507914000
36 startTimeNanos = 512
37
38 latencySec = 5
39 latencyNanos = 123456789
40
41 endTime = startTime + latencySec
42 endTimeNanos = startTimeNanos + latencyNanos
43 )
44 tracer := otel.Tracer("test")
45 ctx, span := tracer.Start(context.Background(), "test")
46 defer span.End()
47 sc := trace.SpanContextFromContext(ctx)
48 buf := new(bytes.Buffer)
49 var logErr error
50 l := NewStackdriverLogger(buf, func(e error) { logErr = e })
51 want := &Entry{
52 ReceivedTime: time.Unix(startTime, startTimeNanos),
53 RequestMethod: "POST",
54 RequestURL: "/foo/bar",
55 RequestHeaderSize: 456,
56 RequestBodySize: 123000,
57 UserAgent: "Chrome proxied through Firefox and Edge",
58 Referer: "http://www.example.com/",
59 Proto: "HTTP/1.1",
60 RemoteIP: "12.34.56.78",
61 ServerIP: "127.0.0.1",
62 Status: 404,
63 ResponseHeaderSize: 555,
64 ResponseBodySize: 789000,
65 Latency: latencySec*time.Second + latencyNanos*time.Nanosecond,
66 TraceID: sc.TraceID(),
67 SpanID: sc.SpanID(),
68 }
69 ent := *want // copy in case Log accidentally mutates
70 l.Log(&ent)
71 if logErr != nil {
72 t.Error("Logger called error callback:", logErr)
73 }
74
75 var got json.RawMessage
76 if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
77 t.Fatal("Unmarshal:", err)
78 }
79
80 var r map[string]any
81 if err := json.Unmarshal(got, &r); err != nil {
82 t.Error("Unmarshal record:", err)
83 } else {
84 rr, _ := r["httpRequest"].(map[string]any)
85 if rr == nil {
86 t.Error("httpRequest does not exist in record or is not a JSON object")
87 }
88 if got, want := jsonString(rr, "requestMethod"), ent.RequestMethod; got != want {
89 t.Errorf("httpRequest.requestMethod = %q; want %q", got, want)
90 }
91 if got, want := jsonString(rr, "requestUrl"), ent.RequestURL; got != want {
92 t.Errorf("httpRequest.requestUrl = %q; want %q", got, want)
93 }
94 if got, want := jsonString(rr, "requestSize"), "123456"; got != want {
95 t.Errorf("httpRequest.requestSize = %q; want %q", got, want)
96 }
97 if got, want := jsonNumber(rr, "status"), float64(ent.Status); got != want {
98 t.Errorf("httpRequest.status = %d; want %d", int64(got), int64(want))
99 }
100 if got, want := jsonString(rr, "responseSize"), "789555"; got != want {
101 t.Errorf("httpRequest.responseSize = %q; want %q", got, want)
102 }
103 if got, want := jsonString(rr, "userAgent"), ent.UserAgent; got != want {
104 t.Errorf("httpRequest.userAgent = %q; want %q", got, want)
105 }
106 if got, want := jsonString(rr, "remoteIp"), ent.RemoteIP; got != want {
107 t.Errorf("httpRequest.remoteIp = %q; want %q", got, want)
108 }
109 if got, want := jsonString(rr, "referer"), ent.Referer; got != want {
110 t.Errorf("httpRequest.referer = %q; want %q", got, want)
111 }
112 if got, want := jsonString(rr, "latency"), "5.123456789"; parseLatency(got) != want {
113 t.Errorf("httpRequest.latency = %q; want %q", got, want+"s")
114 }
115 ts, _ := r["timestamp"].(map[string]any)
116 if ts == nil {
117 t.Error("timestamp does not exist in record or is not a JSON object")
118 }
119 if got, want := jsonNumber(ts, "seconds"), float64(endTime); got != want {
120 t.Errorf("timestamp.seconds = %g; want %g", got, want)
121 }
122 if got, want := jsonNumber(ts, "nanos"), float64(endTimeNanos); got != want {
123 t.Errorf("timestamp.nanos = %g; want %g", got, want)
124 }
125 if got, want := jsonString(r, "logging.googleapis.com/trace"), ent.TraceID.String(); got != want {
126 t.Errorf("traceID = %q; want %q", got, want)
127 }
128 if got, want := jsonString(r, "logging.googleapis.com/spanId"), ent.SpanID.String(); got != want {
129 t.Errorf("spanID = %q; want %q", got, want)
130 }
131 }
132 }
133
134 func parseLatency(s string) string {
135 s = strings.TrimSpace(s)
136 if !strings.HasSuffix(s, "s") {
137 return ""
138 }
139 s = strings.TrimSpace(s[:len(s)-1])
140 for _, c := range s {
141 if !(c >= '0' && c <= '9') && c != '.' {
142 return ""
143 }
144 }
145 return s
146 }
147
148 func jsonString(obj map[string]any, k string) string {
149 v, _ := obj[k].(string)
150 return v
151 }
152
153 func jsonNumber(obj map[string]any, k string) float64 {
154 v, _ := obj[k].(float64)
155 return v
156 }
157
158 func BenchmarkStackdriverLog(b *testing.B) {
159 ent := &Entry{
160 ReceivedTime: time.Date(2017, time.October, 13, 17, 0, 0, 512, time.UTC),
161 RequestMethod: "POST",
162 RequestURL: "/foo/bar",
163 RequestHeaderSize: 456,
164 RequestBodySize: 123000,
165 UserAgent: "Chrome proxied through Firefox and Edge",
166 Referer: "http://www.example.com/",
167 Proto: "HTTP/1.1",
168 RemoteIP: "12.34.56.78",
169 ServerIP: "127.0.0.1",
170 Status: 404,
171 ResponseHeaderSize: 555,
172 ResponseBodySize: 789000,
173 Latency: 5 * time.Second,
174 }
175 var buf bytes.Buffer
176 l := NewStackdriverLogger(&buf, func(error) {})
177 l.Log(ent)
178 b.ReportAllocs()
179 b.SetBytes(int64(buf.Len()))
180 buf.Reset()
181 b.ResetTimer()
182
183 l = NewStackdriverLogger(io.Discard, func(error) {})
184 for i := 0; i < b.N; i++ {
185 l.Log(ent)
186 }
187 }
188
189 func BenchmarkE2E(b *testing.B) {
190 run := func(b *testing.B, handler http.Handler) {
191 b.Helper()
192
193 s := httptest.NewServer(handler)
194 defer s.Close()
195 b.ReportAllocs()
196 for i := 0; i < b.N; i++ {
197 resp, err := http.Get(s.URL)
198 if err != nil {
199 b.Fatal(err)
200 }
201 _, _ = io.Copy(io.Discard, resp.Body)
202 _ = resp.Body.Close()
203 }
204 }
205 b.Run("Baseline", func(b *testing.B) {
206 run(b, http.HandlerFunc(benchHandler))
207 })
208 b.Run("WithLog", func(b *testing.B) {
209 l := NewStackdriverLogger(io.Discard, func(error) {})
210 run(b, NewHandler(l, http.HandlerFunc(benchHandler)))
211 })
212 }
213
214 func benchHandler(w http.ResponseWriter, r *http.Request) {
215 const msg = "Hello, World!"
216 w.Header().Set("Content-Length", fmt.Sprint(len(msg)))
217 _, _ = io.WriteString(w, msg)
218 }