Skip to content

Commit

Permalink
Use zerolog logger http handlers and set timeout handler
Browse files Browse the repository at this point in the history
Replace custom logger middleware with zerolog/hlog solutions.
Use logger instance from the HTTP request.
  • Loading branch information
miry committed Aug 28, 2022
1 parent 5be63bd commit 805fe34
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 41 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Support go 1.18, 1.19. (@miry)
* `toxiproxy.NewProxy` now accepts `name`, `listen addr` and `upstream addr`. (#418, @miry)
* Replace logrus with zerolog. (#413, @miry)
* Log HTTP requests to API server. (#413, @miry)
* Log HTTP requests to API server. (#413, #421, @miry)
* Add TimeoutHandler for the HTTP API server. (#420, @miry)

# [2.4.0] - 2022-03-07
Expand Down
66 changes: 39 additions & 27 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

"github.com/gorilla/mux"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog"

"github.com/Shopify/toxiproxy/v2/toxics"
)
Expand Down Expand Up @@ -61,7 +62,18 @@ func timeoutMiddleware(next http.Handler) http.Handler {

func (server *ApiServer) Listen(host string, port string) {
r := mux.NewRouter()
r.Use(server.loggingMiddleware)
r.Use(hlog.NewHandler(*server.Logger))
r.Use(hlog.RequestIDHandler("request_id", ""))
r.Use(hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {
hlog.FromRequest(r).Debug().
Str("client", r.RemoteAddr).
Str("method", r.Method).
Stringer("url", r.URL).
Int("status", status).
Int("size", size).
Dur("duration", duration).
Msg("")
}))
r.Use(timeoutMiddleware)

r.HandleFunc("/reset", server.ResetState).Methods("POST")
Expand Down Expand Up @@ -98,19 +110,6 @@ func (server *ApiServer) Listen(host string, port string) {
}
}

func (server *ApiServer) loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
server.
Logger.
Debug().
Str("client", r.RemoteAddr).
Str("method", r.Method).
Str("uri", r.RequestURI).
Msg("")
next.ServeHTTP(w, r)
})
}

func (server *ApiServer) ProxyIndex(response http.ResponseWriter, request *http.Request) {
proxies := server.Collection.Proxies()
marshalData := make(map[string]interface{}, len(proxies))
Expand All @@ -127,7 +126,8 @@ func (server *ApiServer) ProxyIndex(response http.ResponseWriter, request *http.
response.Header().Set("Content-Type", "application/json")
_, err = response.Write(data)
if err != nil {
server.Logger.Warn().Err(err).Msg("ProxyIndex: Failed to write response to client")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("ProxyIndex: Failed to write response to client")
}
}

Expand All @@ -146,7 +146,8 @@ func (server *ApiServer) ResetState(response http.ResponseWriter, request *http.
response.WriteHeader(http.StatusNoContent)
_, err := response.Write(nil)
if err != nil {
server.Logger.Warn().Err(err).Msg("ResetState: Failed to write headers to client")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("ResetState: Failed to write headers to client")
}
}

Expand Down Expand Up @@ -183,7 +184,8 @@ func (server *ApiServer) ProxyCreate(response http.ResponseWriter, request *http
response.WriteHeader(http.StatusCreated)
_, err = response.Write(data)
if err != nil {
server.Logger.Warn().Err(err).Msg("ProxyCreate: Failed to write response to client")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("ProxyCreate: Failed to write response to client")
}
}

Expand All @@ -192,7 +194,8 @@ func (server *ApiServer) Populate(response http.ResponseWriter, request *http.Re

apiErr, ok := err.(*ApiError)
if !ok && err != nil {
server.Logger.Warn().Err(err).Msg("Error did not include status code")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("Error did not include status code")
apiErr = &ApiError{err.Error(), http.StatusInternalServerError}
}

Expand All @@ -213,7 +216,8 @@ func (server *ApiServer) Populate(response http.ResponseWriter, request *http.Re
response.WriteHeader(responseCode)
_, err = response.Write(data)
if err != nil {
server.Logger.Warn().Err(err).Msg("Populate: Failed to write response to client")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("Populate: Failed to write response to client")
}
}

Expand Down Expand Up @@ -265,7 +269,8 @@ func (server *ApiServer) ProxyUpdate(response http.ResponseWriter, request *http
response.Header().Set("Content-Type", "application/json")
_, err = response.Write(data)
if err != nil {
server.Logger.Warn().Err(err).Msg("ProxyUpdate: Failed to write response to client")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("ProxyUpdate: Failed to write response to client")
}
}

Expand All @@ -280,7 +285,8 @@ func (server *ApiServer) ProxyDelete(response http.ResponseWriter, request *http
response.WriteHeader(http.StatusNoContent)
_, err = response.Write(nil)
if err != nil {
server.Logger.Warn().Err(err).Msg("ProxyDelete: Failed to write headers to client")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("ProxyDelete: Failed to write headers to client")
}
}

Expand All @@ -301,7 +307,8 @@ func (server *ApiServer) ToxicIndex(response http.ResponseWriter, request *http.
response.Header().Set("Content-Type", "application/json")
_, err = response.Write(data)
if err != nil {
server.Logger.Warn().Err(err).Msg("ToxicIndex: Failed to write response to client")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("ToxicIndex: Failed to write response to client")
}
}

Expand All @@ -326,7 +333,8 @@ func (server *ApiServer) ToxicCreate(response http.ResponseWriter, request *http
response.Header().Set("Content-Type", "application/json")
_, err = response.Write(data)
if err != nil {
server.Logger.Warn().Err(err).Msg("ToxicCreate: Failed to write response to client")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("ToxicCreate: Failed to write response to client")
}
}

Expand All @@ -352,7 +360,8 @@ func (server *ApiServer) ToxicShow(response http.ResponseWriter, request *http.R
response.Header().Set("Content-Type", "application/json")
_, err = response.Write(data)
if err != nil {
server.Logger.Warn().Err(err).Msg("ToxicShow: Failed to write response to client")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("ToxicShow: Failed to write response to client")
}
}

Expand All @@ -377,7 +386,8 @@ func (server *ApiServer) ToxicUpdate(response http.ResponseWriter, request *http
response.Header().Set("Content-Type", "application/json")
_, err = response.Write(data)
if err != nil {
server.Logger.Warn().Err(err).Msg("ToxicUpdate: Failed to write response to client")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("ToxicUpdate: Failed to write response to client")
}
}

Expand All @@ -397,15 +407,17 @@ func (server *ApiServer) ToxicDelete(response http.ResponseWriter, request *http
response.WriteHeader(http.StatusNoContent)
_, err = response.Write(nil)
if err != nil {
server.Logger.Warn().Err(err).Msg("ToxicDelete: Failed to write headers to client")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("ToxicDelete: Failed to write headers to client")
}
}

func (server *ApiServer) Version(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "text/plain;charset=utf-8")
_, err := response.Write([]byte(Version))
if err != nil {
server.Logger.Warn().Err(err).Msg("Version: Failed to write response to client")
log := zerolog.Ctx(request.Context())
log.Warn().Err(err).Msg("Version: Failed to write response to client")
}
}

Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ require (
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.35.0 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/rs/xid v1.3.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d // indirect
Expand Down
14 changes: 1 addition & 13 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,9 @@ github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMn
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU=
github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
Expand Down Expand Up @@ -169,7 +166,6 @@ github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRW
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
Expand All @@ -196,6 +192,7 @@ github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1
github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU=
github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rs/xid v1.3.0 h1:6NjYksEUlhurdVehpc7S7dk6DAmcKv8V9gG0FsVN2U4=
github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.27.0 h1:1T7qCieN22GVc8S4Q2yuexzBb1EqjbgjSH9RohbMjKs=
github.com/rs/zerolog v1.27.0/go.mod h1:7frBqO0oezxmnO7GF86FY++uy8I0Tk/If5ni1G9Qc0U=
Expand All @@ -204,16 +201,11 @@ github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/urfave/cli/v2 v2.4.0 h1:m2pxjjDFgDxSPtO8WSdbndj17Wu2y8vOT86wE/tjr+I=
github.com/urfave/cli/v2 v2.4.0/go.mod h1:NX9W0zmTvedE5oDoOMs2RTC8RvdK98NTYZE5LbaEYPg=
github.com/urfave/cli/v2 v2.11.0 h1:c6bD90aLd2iEsokxhxkY5Er0zA2V9fId2aJfwmrF+do=
github.com/urfave/cli/v2 v2.11.0/go.mod h1:f8iq5LtQ/bLxafbdBSLPPNsgaW0l/2fYYEHhAyPlwvo=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=
Expand Down Expand Up @@ -322,7 +314,6 @@ golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Expand Down Expand Up @@ -353,7 +344,6 @@ golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d h1:/m5NbqQelATgoSPVC2Z23sR4kVNokFwDDyWh/3rGY+I=
golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.0.0-20220526004731-065cf7ba2467 h1:CBpWXWQpIRjzmkkA+M7q9Fqnwd2mZr3AFqexg8YTfoM=
golang.org/x/term v0.0.0-20220526004731-065cf7ba2467/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
Expand Down Expand Up @@ -500,9 +490,7 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Expand Down

0 comments on commit 805fe34

Please sign in to comment.