From 524f58c78cd05d75506fbefe8b0d2d52e80c8abe Mon Sep 17 00:00:00 2001 From: Aliaksandr Valialkin Date: Sat, 5 Jul 2025 23:49:02 +0200 Subject: [PATCH] lib/httpserver: log the client address additionally to the requestURI in the SendPrometheusError() This should allow detecting the client, which led to the error logged via SendPrometheusError() function, e.g. this improves troubleshooting of the logged errors. This is a follow-up for c9bb4ddeed6f6e8463bab9854b4565d7f788719a --- lib/httpserver/httpserver.go | 13 +++++++++---- lib/httpserver/prometheus.go | 5 ++--- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/httpserver/httpserver.go b/lib/httpserver/httpserver.go index 67266fc756..9c8a6778a3 100644 --- a/lib/httpserver/httpserver.go +++ b/lib/httpserver/httpserver.go @@ -653,10 +653,7 @@ func (rwa *responseWriterWithAbort) abort() { // Errorf writes formatted error message to w and to logger. func Errorf(w http.ResponseWriter, r *http.Request, format string, args ...any) { errStr := fmt.Sprintf(format, args...) - remoteAddr := GetQuotedRemoteAddr(r) - requestURI := GetRequestURI(r) - errStr = fmt.Sprintf("remoteAddr: %s; requestURI: %s; %s", remoteAddr, requestURI, errStr) - logger.WarnfSkipframes(1, "%s", errStr) + logHTTPError(r, errStr) // Extract statusCode from args statusCode := http.StatusBadRequest @@ -678,6 +675,14 @@ func Errorf(w http.ResponseWriter, r *http.Request, format string, args ...any) http.Error(w, errStr, statusCode) } +// logHTTPError logs the errStr with the client remote address and the request URI obtained from r. +func logHTTPError(r *http.Request, errStr string) { + remoteAddr := GetQuotedRemoteAddr(r) + requestURI := GetRequestURI(r) + errStr = fmt.Sprintf("remoteAddr: %s; requestURI: %s; %s", remoteAddr, requestURI, errStr) + logger.WarnfSkipframes(2, "%s", errStr) +} + // ErrorWithStatusCode is error with HTTP status code. // // The given StatusCode is sent to client when the error is passed to Errorf. diff --git a/lib/httpserver/prometheus.go b/lib/httpserver/prometheus.go index 08c5e32afe..591603381d 100644 --- a/lib/httpserver/prometheus.go +++ b/lib/httpserver/prometheus.go @@ -3,15 +3,14 @@ package httpserver import ( "errors" "net/http" - - "github.com/VictoriaMetrics/VictoriaMetrics/lib/logger" ) // SendPrometheusError sends err to w in Prometheus querying API response format. // // See https://prometheus.io/docs/prometheus/latest/querying/api/#format-overview for more details func SendPrometheusError(w http.ResponseWriter, r *http.Request, err error) { - logger.WarnfSkipframes(1, "error in %q: %s", GetRequestURI(r), err) + errStr := err.Error() + logHTTPError(r, errStr) w.Header().Set("Content-Type", "application/json") statusCode := http.StatusUnprocessableEntity