Skip to content

Instantly share code, notes, and snippets.

@theruziev
Created May 7, 2022 22:16
Show Gist options
  • Save theruziev/cb0cfcd7d8a2d939e04e549137b75009 to your computer and use it in GitHub Desktop.
Save theruziev/cb0cfcd7d8a2d939e04e549137b75009 to your computer and use it in GitHub Desktop.
package logger
import (
"bytes"
"fmt"
"io"
"net/http"
"time"
"github.com/go-chi/chi/v5/middleware"
"github.com/sirupsen/logrus"
)
const maxBodyLog = 512
// HTTPMiddleware ...
func HTTPMiddleware(logBody bool) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
l := GetLogger(r.Context())
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
requestFields := logrus.Fields{
"uri": fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI),
"http_proto": r.Proto,
"http_method": r.Method,
"remote_addr": r.RemoteAddr,
"user_agent": r.UserAgent(),
}
if logBody {
body, err := io.ReadAll(r.Body)
if err != nil {
l.WithError(err).Error("failed read body")
} else {
r.Body = io.NopCloser(bytes.NewBuffer(body))
}
if len(body) > 0 {
requestFields["request_body"] = bodyWithLimit(body, maxBodyLog)
}
}
l = l.WithFields(requestFields)
responseBodyBuffer := bytes.NewBufferString("")
if logBody {
w = &responseWriterWithBodyReader{
ResponseWriter: w,
body: responseBodyBuffer,
}
}
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
startTime := time.Now()
next.ServeHTTP(ww, r.WithContext(SetLogger(r.Context(), l)))
responseFields := logrus.Fields{
"response_status": ww.Status(),
"response_bytes_length": ww.BytesWritten(),
"response_elapsed_ms": float64(time.Since(startTime).Nanoseconds()) / 1e6,
}
if logBody && responseBodyBuffer.Len() > 0 {
responseFields["response_body"] = bodyWithLimit(responseBodyBuffer.Bytes(), maxBodyLog)
}
l = l.WithFields(responseFields)
l.Debug("request")
SetLogger(r.Context(), l)
}
return http.HandlerFunc(fn)
}
}
type responseWriterWithBodyReader struct {
http.ResponseWriter
body *bytes.Buffer
}
func (r *responseWriterWithBodyReader) Write(b []byte) (int, error) {
r.body.Write(b)
return r.ResponseWriter.Write(b)
}
func bodyWithLimit(b []byte, n int) string {
if len(b) > n {
return string(b[:512])
}
return string(b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment