Skip to content

Commit

Permalink
Should log decider for http middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Raymond Wongso committed Apr 6, 2023
1 parent fe5d61b commit c6555b8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
8 changes: 6 additions & 2 deletions http/log/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func (r *loggingResponseWriter) WriteHeader(statusCode int) {
}

// LoggingMiddleware provides log middleware that log request and response.
func LoggingMiddleware(logger log.Logger, handler http.Handler) http.Handler {
func LoggingMiddleware(logger log.Logger, handler http.Handler, opts options) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
md := newLogMetadata(r, startTime)
Expand All @@ -40,9 +40,13 @@ func LoggingMiddleware(logger log.Logger, handler http.Handler) http.Handler {

handler.ServeHTTP(lrw, r)

status := lrw.status
if !opts.ShouldLog(r, status) {
return
}

duration_ms := float32(time.Since(startTime).Nanoseconds()/1000) / 1000
size := lrw.size
status := lrw.status

// TODO(raymondwongso) research more about status in integration with grpc gateway, somehow status is 0
// for now, override to 200 assuming it is a successful request
Expand Down
8 changes: 4 additions & 4 deletions http/log/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
)

// Decider defines rules for surpressing log
type Decider func(req *http.Request, err error) bool
type Decider func(req *http.Request, status int) bool

type options struct {
ShouldLog Decider
Expand All @@ -20,15 +20,15 @@ func DefaultOptions() options {

// DefaultDecider returns always true decider
func DefaultDecider() Decider {
return func(req *http.Request, err error) bool {
return func(req *http.Request, status int) bool {
return true
}
}

// SkipPrometheusDecider returns common skip prometheus /metric
func SkipPrometheusDecider() Decider {
return func(req *http.Request, err error) bool {
if err == nil && req.URL.Path == "/metrics" {
return func(req *http.Request, status int) bool {
if status == 200 && req.URL.Path == "/metrics" {
return false
}
return true
Expand Down

0 comments on commit c6555b8

Please sign in to comment.