"bytes"
"context"
"encoding/json"
+ "fmt"
"net/http"
"net/http/httptest"
"testing"
var _ = check.Suite(&Suite{})
-type Suite struct{}
+type Suite struct {
+ ctx context.Context
+ log *logrus.Logger
+ logdata *bytes.Buffer
+}
-func (s *Suite) TestLogRequests(c *check.C) {
- captured := &bytes.Buffer{}
- log := logrus.New()
- log.Out = captured
- log.Formatter = &logrus.JSONFormatter{
+func (s *Suite) SetUpTest(c *check.C) {
+ s.logdata = bytes.NewBuffer(nil)
+ s.log = logrus.New()
+ s.log.Out = s.logdata
+ s.log.Formatter = &logrus.JSONFormatter{
TimestampFormat: time.RFC3339Nano,
}
- ctx := ctxlog.Context(context.Background(), log)
+ s.ctx = ctxlog.Context(context.Background(), s.log)
+}
+func (s *Suite) TestLogRequests(c *check.C) {
h := AddRequestIDs(LogRequests(
http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("hello world"))
c.Assert(err, check.IsNil)
resp := httptest.NewRecorder()
- HandlerWithContext(ctx, h).ServeHTTP(resp, req)
+ HandlerWithContext(s.ctx, h).ServeHTTP(resp, req)
- dec := json.NewDecoder(captured)
+ dec := json.NewDecoder(s.logdata)
gotReq := make(map[string]interface{})
err = dec.Decode(&gotReq)
c.Check(gotResp[key].(float64), check.Not(check.Equals), float64(0))
}
}
+
+func (s *Suite) TestLogErrorBody(c *check.C) {
+ dec := json.NewDecoder(s.logdata)
+
+ for _, trial := range []struct {
+ label string
+ statusCode int
+ sentBody string
+ expectLog bool
+ expectBody string
+ }{
+ {"ok", 200, "hello world", false, ""},
+ {"redir", 302, "<a href='http://foo.example/baz'>redir</a>", false, ""},
+ {"4xx short body", 400, "oops", true, "oops"},
+ {"4xx long body", 400, fmt.Sprintf("%0*d", sniffBytes*2, 1), true, fmt.Sprintf("%0*d", sniffBytes, 0)},
+ {"5xx empty body", 500, "", true, ""},
+ } {
+ comment := check.Commentf("in trial: %q", trial.label)
+
+ req, err := http.NewRequest("GET", "https://foo.example/bar", nil)
+ c.Assert(err, check.IsNil)
+ resp := httptest.NewRecorder()
+
+ HandlerWithContext(s.ctx, LogRequests(
+ http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ w.WriteHeader(trial.statusCode)
+ w.Write([]byte(trial.sentBody))
+ }),
+ )).ServeHTTP(resp, req)
+
+ gotReq := make(map[string]interface{})
+ err = dec.Decode(&gotReq)
+ c.Logf("%#v", gotReq)
+ gotResp := make(map[string]interface{})
+ err = dec.Decode(&gotResp)
+ c.Logf("%#v", gotResp)
+ if trial.expectLog {
+ c.Check(gotResp["respBody"], check.Equals, trial.expectBody, comment)
+ } else {
+ c.Check(gotResp["respBody"], check.IsNil, comment)
+ }
+ }
+}
"net/http"
)
+const sniffBytes = 1024
+
type ResponseWriter interface {
http.ResponseWriter
WroteStatus() int
WroteBodyBytes() int
+ Sniffed() []byte
}
// responseWriter wraps http.ResponseWriter and exposes the status
wroteStatus int // Last status given to WriteHeader()
wroteBodyBytes int // Bytes successfully written
err error // Last error returned from Write()
+ sniffed []byte
}
func WrapResponseWriter(orig http.ResponseWriter) ResponseWriter {
if w.wroteStatus == 0 {
w.WriteHeader(http.StatusOK)
}
+ w.sniff(data)
n, err = w.ResponseWriter.Write(data)
w.wroteBodyBytes += n
w.err = err
func (w *responseWriter) Err() error {
return w.err
}
+
+func (w *responseWriter) sniff(data []byte) {
+ max := sniffBytes - len(w.sniffed)
+ if max <= 0 {
+ return
+ } else if max < len(data) {
+ data = data[:max]
+ }
+ w.sniffed = append(w.sniffed, data...)
+}
+
+func (w *responseWriter) Sniffed() []byte {
+ return w.sniffed
+}