All checks were successful
/ DCO (pull_request) Successful in 1m47s
/ Vulncheck (pull_request) Successful in 1m48s
/ Lint (pull_request) Successful in 3m52s
/ Tests (1.20) (pull_request) Successful in 2m22s
/ Tests (1.21) (pull_request) Successful in 2m20s
/ Builds (1.20) (pull_request) Successful in 1m15s
/ Builds (1.21) (pull_request) Successful in 1m32s
Signed-off-by: Nikita Zinkevich <n.zinkevich@yadro.com>
61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
|
|
"git.frostfs.info/TrueCloudLab/frostfs-s3-gw/internal/logs"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
type LogHTTPSettings struct {
|
|
Enabled bool
|
|
MaxBody int64
|
|
}
|
|
|
|
// LogHTTP logs http parameters from s3 request.
|
|
func LogHTTP(l *zap.Logger, settings LogHTTPSettings) Func {
|
|
return func(h http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if !settings.Enabled {
|
|
h.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
var httplog = l.With(
|
|
zap.String("from", r.RemoteAddr),
|
|
zap.String("URI", r.RequestURI),
|
|
zap.String("method", r.Method),
|
|
)
|
|
|
|
httplog = withFieldIfExist(httplog, "query", r.URL.Query())
|
|
httplog = withFieldIfExist(httplog, "headers", r.Header)
|
|
if r.ContentLength != 0 && r.ContentLength <= settings.MaxBody {
|
|
var err error
|
|
httplog, err = withBody(httplog, r)
|
|
if err != nil {
|
|
l.Error("read body error")
|
|
}
|
|
}
|
|
httplog.Info(logs.RequestHTTP)
|
|
h.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|
|
|
|
func withBody(httplog *zap.Logger, r *http.Request) (*zap.Logger, error) {
|
|
var body = make([]byte, r.ContentLength)
|
|
_, err := r.Body.Read(body)
|
|
if err != nil && err != io.EOF {
|
|
return nil, err
|
|
}
|
|
httplog = httplog.With(zap.String("body", string(body)))
|
|
|
|
return httplog, nil
|
|
}
|
|
|
|
func withFieldIfExist(log *zap.Logger, label string, data map[string][]string) *zap.Logger {
|
|
if len(data) != 0 {
|
|
log = log.With(zap.Any(label, data))
|
|
}
|
|
return log
|
|
}
|