2023-10-14 16:06:02 +00:00
|
|
|
package middlewares
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
2024-08-15 16:25:15 +00:00
|
|
|
"go.uber.org/zap"
|
2023-10-14 16:06:02 +00:00
|
|
|
)
|
|
|
|
|
2023-10-15 15:49:33 +00:00
|
|
|
type loggedResponseWriter struct {
|
|
|
|
w http.ResponseWriter
|
|
|
|
statusCode int
|
|
|
|
contentLength int
|
|
|
|
}
|
|
|
|
|
|
|
|
func (lr *loggedResponseWriter) Header() http.Header {
|
|
|
|
return lr.w.Header()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (lr *loggedResponseWriter) Write(dat []byte) (int, error) {
|
|
|
|
if lr.statusCode < 100 {
|
|
|
|
lr.statusCode = http.StatusOK
|
|
|
|
}
|
|
|
|
res, err := lr.w.Write(dat)
|
|
|
|
lr.contentLength += res
|
|
|
|
return res, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (lr *loggedResponseWriter) WriteHeader(statusCode int) {
|
|
|
|
lr.statusCode = statusCode
|
|
|
|
lr.w.WriteHeader(statusCode)
|
2023-10-14 16:06:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type LoggerMiddleware struct {
|
2024-08-15 16:25:15 +00:00
|
|
|
l *zap.SugaredLogger
|
2023-10-15 15:49:33 +00:00
|
|
|
h http.Handler
|
2023-10-14 16:06:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (lm *LoggerMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2023-10-15 15:49:33 +00:00
|
|
|
recorder := loggedResponseWriter{
|
2023-10-15 18:11:50 +00:00
|
|
|
contentLength: 0,
|
2023-10-15 15:49:33 +00:00
|
|
|
statusCode: -1,
|
|
|
|
w: w,
|
2023-10-14 16:06:02 +00:00
|
|
|
}
|
2023-10-15 15:49:33 +00:00
|
|
|
lm.h.ServeHTTP(&recorder, r)
|
|
|
|
|
2023-10-14 16:06:02 +00:00
|
|
|
method := r.Method
|
|
|
|
route := r.RequestURI
|
|
|
|
currentTime := time.Now().UTC()
|
|
|
|
httpVersion := r.Proto
|
|
|
|
|
|
|
|
clientIP, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
|
|
if err != nil {
|
|
|
|
lm.l.Errorf("Failed to read remote IP: %s", err.Error())
|
|
|
|
clientIP = "unknown"
|
|
|
|
}
|
|
|
|
|
2023-10-15 15:49:33 +00:00
|
|
|
lm.l.Infof(`%s - [%s] "%s %s %s" %d %d`, clientIP, currentTime.Format(time.RFC3339), method, route, httpVersion, recorder.statusCode, recorder.contentLength)
|
2023-10-14 16:06:02 +00:00
|
|
|
}
|