1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
16 log "github.com/Sirupsen/logrus"
17 check "gopkg.in/check.v1"
20 func Test(t *testing.T) {
24 var _ = check.Suite(&Suite{})
28 func (s *Suite) TestLogRequests(c *check.C) {
29 defer log.SetOutput(os.Stdout)
30 captured := &bytes.Buffer{}
31 log.SetOutput(captured)
32 log.SetFormatter(&log.JSONFormatter{
33 TimestampFormat: time.RFC3339Nano,
35 h := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
36 w.Write([]byte("hello world"))
38 req, err := http.NewRequest("GET", "https://foo.example/bar", nil)
39 req.Header.Set("X-Forwarded-For", "1.2.3.4:12345")
40 c.Assert(err, check.IsNil)
41 resp := httptest.NewRecorder()
42 AddRequestIDs(LogRequests(h)).ServeHTTP(resp, req)
44 dec := json.NewDecoder(captured)
46 gotReq := make(map[string]interface{})
47 err = dec.Decode(&gotReq)
49 c.Check(gotReq["RequestID"], check.Matches, "req-[a-z0-9]{20}")
50 c.Check(gotReq["reqForwardedFor"], check.Equals, "1.2.3.4:12345")
51 c.Check(gotReq["msg"], check.Equals, "request")
53 gotResp := make(map[string]interface{})
54 err = dec.Decode(&gotResp)
55 c.Logf("%#v", gotResp)
56 c.Check(gotResp["RequestID"], check.Equals, gotReq["RequestID"])
57 c.Check(gotResp["reqForwardedFor"], check.Equals, "1.2.3.4:12345")
58 c.Check(gotResp["msg"], check.Equals, "response")
60 c.Assert(gotResp["time"], check.FitsTypeOf, "")
61 _, err = time.Parse(time.RFC3339Nano, gotResp["time"].(string))
62 c.Check(err, check.IsNil)
64 for _, key := range []string{"timeToStatus", "timeWriteBody", "timeTotal"} {
65 c.Assert(gotResp[key], check.FitsTypeOf, float64(0))
66 c.Check(gotResp[key].(float64), check.Not(check.Equals), float64(0))