polycule-connect/polyculeconnect/internal/middlewares/logger.go

61 lines
1.3 KiB
Go
Raw Permalink Normal View History

2023-10-14 16:06:02 +00:00
package middlewares
import (
"net"
"net/http"
"time"
"go.uber.org/zap"
2023-10-14 16:06:02 +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 {
l *zap.SugaredLogger
h http.Handler
2023-10-14 16:06:02 +00:00
}
func (lm *LoggerMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
recorder := loggedResponseWriter{
2023-10-15 18:11:50 +00:00
contentLength: 0,
statusCode: -1,
w: w,
2023-10-14 16:06:02 +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"
}
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
}