github.com/koko1123/flow-go-1@v0.29.6/engine/access/rest/middleware/logging.go (about)

     1  package middleware
     2  
     3  import (
     4  	"net/http"
     5  	"time"
     6  
     7  	"github.com/gorilla/mux"
     8  	"github.com/rs/zerolog"
     9  )
    10  
    11  // LoggingMiddleware creates a middleware which adds a logger interceptor to each request to log the request method, uri,
    12  // duration and response code
    13  func LoggingMiddleware(logger zerolog.Logger) mux.MiddlewareFunc {
    14  	return func(inner http.Handler) http.Handler {
    15  		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    16  			// record star time
    17  			start := time.Now()
    18  			// modify the writer
    19  			respWriter := newResponseWriter(w)
    20  			// continue to the next handler
    21  			inner.ServeHTTP(respWriter, req)
    22  			log := logger.Info()
    23  			if respWriter.statusCode != http.StatusOK {
    24  				log = logger.Error()
    25  			}
    26  			log.Str("method", req.Method).
    27  				Str("uri", req.RequestURI).
    28  				Str("client_ip", req.RemoteAddr).
    29  				Str("user_agent", req.UserAgent()).
    30  				Dur("duration", time.Since(start)).
    31  				Int("response_code", respWriter.statusCode).
    32  				Msg("api")
    33  		})
    34  	}
    35  }
    36  
    37  // responseWriter is a wrapper around http.ResponseWriter and helps capture the response code
    38  type responseWriter struct {
    39  	http.ResponseWriter
    40  	statusCode int
    41  }
    42  
    43  func newResponseWriter(w http.ResponseWriter) *responseWriter {
    44  	return &responseWriter{w, http.StatusOK}
    45  }
    46  
    47  func (rw *responseWriter) WriteHeader(code int) {
    48  	rw.statusCode = code
    49  	rw.ResponseWriter.WriteHeader(code)
    50  }