Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use common logging middleware #6865

Merged
merged 7 commits into from
Jan 22, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 3 additions & 27 deletions ee/query-service/app/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (
"go.signoz.io/signoz/ee/query-service/integrations/gateway"
"go.signoz.io/signoz/ee/query-service/interfaces"
"go.signoz.io/signoz/ee/query-service/rules"
"go.signoz.io/signoz/pkg/http/middleware"
baseauth "go.signoz.io/signoz/pkg/query-service/auth"
v3 "go.signoz.io/signoz/pkg/query-service/model/v3"
"go.signoz.io/signoz/pkg/signoz"
Expand Down Expand Up @@ -321,7 +322,7 @@ func (s *Server) createPrivateServer(apiHandler *api.APIHandler) (*http.Server,

r.Use(setTimeoutMiddleware)
r.Use(s.analyticsMiddleware)
r.Use(loggingMiddlewarePrivate)
r.Use(middleware.NewLogging(zap.L(), zap.Bool("privatePort", true)).Wrap)
r.Use(baseapp.LogCommentEnricher)

apiHandler.RegisterPrivateRoutes(r)
Expand Down Expand Up @@ -364,7 +365,7 @@ func (s *Server) createPublicServer(apiHandler *api.APIHandler, web web.Web) (*h

r.Use(setTimeoutMiddleware)
r.Use(s.analyticsMiddleware)
r.Use(loggingMiddleware)
r.Use(middleware.NewLogging(zap.L()).Wrap)
r.Use(baseapp.LogCommentEnricher)

apiHandler.RegisterRoutes(r, am)
Expand Down Expand Up @@ -397,31 +398,6 @@ func (s *Server) createPublicServer(apiHandler *api.APIHandler, web web.Web) (*h
}, nil
}

// TODO(remove): Implemented at pkg/http/middleware/logging.go
// loggingMiddleware is used for logging public api calls
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
startTime := time.Now()
next.ServeHTTP(w, r)
zap.L().Info(path, zap.Duration("timeTaken", time.Since(startTime)), zap.String("path", path))
})
}

// TODO(remove): Implemented at pkg/http/middleware/logging.go
// loggingMiddlewarePrivate is used for logging private api calls
// from internal services like alert manager
func loggingMiddlewarePrivate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
startTime := time.Now()
next.ServeHTTP(w, r)
zap.L().Info(path, zap.Duration("timeTaken", time.Since(startTime)), zap.String("path", path), zap.Bool("tprivatePort", true))
})
}

// TODO(remove): Implemented at pkg/http/middleware/logging.go
type loggingResponseWriter struct {
http.ResponseWriter
Expand Down
19 changes: 11 additions & 8 deletions pkg/http/middleware/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,23 @@ const (

type Logging struct {
logger *zap.Logger
// staticFields are additional fields that will be included in every log entry
staticFields []zap.Field
}

func NewLogging(logger *zap.Logger) *Logging {
func NewLogging(logger *zap.Logger, staticFields ...zap.Field) *Logging {
nityanandagohain marked this conversation as resolved.
Show resolved Hide resolved
if logger == nil {
panic("cannot build logging, logger is empty")
}

return &Logging{
logger: logger.Named(pkgname),
logger: logger.Named(pkgname),
staticFields: staticFields,
}
}

func (middleware *Logging) Wrap(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
start := time.Now()
host, port, _ := net.SplitHostPort(req.Host)
path, err := mux.CurrentRoute(req).GetPathTemplate()
Expand All @@ -40,17 +42,17 @@ func (middleware *Logging) Wrap(next http.Handler) http.Handler {
}

fields := []zap.Field{
zap.Any("context", ctx),
zap.String(string(semconv.ClientAddressKey), req.RemoteAddr),
zap.String(string(semconv.UserAgentOriginalKey), req.UserAgent()),
zap.String(string(semconv.ServerAddressKey), host),
zap.String(string(semconv.ServerPortKey), port),
zap.Int64(string(semconv.HTTPRequestSizeKey), req.ContentLength),
zap.String(string(semconv.HTTPRouteKey), path),
}
fields = append(fields, middleware.staticFields...)

buf := new(bytes.Buffer)
writer := newBadResponseLoggingWriter(rw, buf)
badResponseBuffer := new(bytes.Buffer)
nityanandagohain marked this conversation as resolved.
Show resolved Hide resolved
writer := newBadResponseLoggingWriter(rw, badResponseBuffer)
next.ServeHTTP(writer, req)

statusCode, err := writer.StatusCode(), writer.WriteError()
Expand All @@ -62,8 +64,9 @@ func (middleware *Logging) Wrap(next http.Handler) http.Handler {
fields = append(fields, zap.Error(err))
middleware.logger.Error(logMessage, fields...)
} else {
if buf.Len() != 0 {
fields = append(fields, zap.String("response.body", buf.String()))
// when the status code is 400 or >=500, and the response body is not empty.
if badResponseBuffer.Len() != 0 {
fields = append(fields, zap.String("response.body", badResponseBuffer.String()))
}

middleware.logger.Info(logMessage, fields...)
Expand Down
30 changes: 3 additions & 27 deletions pkg/query-service/app/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (

"github.com/rs/cors"
"github.com/soheilhy/cmux"
"go.signoz.io/signoz/pkg/http/middleware"
"go.signoz.io/signoz/pkg/query-service/agentConf"
"go.signoz.io/signoz/pkg/query-service/app/clickhouseReader"
"go.signoz.io/signoz/pkg/query-service/app/cloudintegrations"
Expand Down Expand Up @@ -265,7 +266,7 @@ func (s *Server) createPrivateServer(api *APIHandler) (*http.Server, error) {

r.Use(setTimeoutMiddleware)
r.Use(s.analyticsMiddleware)
r.Use(loggingMiddlewarePrivate)
r.Use(middleware.NewLogging(zap.L(), zap.Bool("privatePort", true)).Wrap)

api.RegisterPrivateRoutes(r)

Expand All @@ -291,7 +292,7 @@ func (s *Server) createPublicServer(api *APIHandler, web web.Web) (*http.Server,

r.Use(setTimeoutMiddleware)
r.Use(s.analyticsMiddleware)
r.Use(loggingMiddleware)
r.Use(middleware.NewLogging(zap.L()).Wrap)
r.Use(LogCommentEnricher)

// add auth middleware
Expand Down Expand Up @@ -340,18 +341,6 @@ func (s *Server) createPublicServer(api *APIHandler, web web.Web) (*http.Server,
}, nil
}

// TODO(remove): Implemented at pkg/http/middleware/logging.go
// loggingMiddleware is used for logging public api calls
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
startTime := time.Now()
next.ServeHTTP(w, r)
zap.L().Info(path, zap.Duration("timeTaken", time.Since(startTime)), zap.String("path", path))
})
}

func LogCommentEnricher(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
referrer := r.Header.Get("Referer")
Expand Down Expand Up @@ -414,19 +403,6 @@ func LogCommentEnricher(next http.Handler) http.Handler {
})
}

// TODO(remove): Implemented at pkg/http/middleware/logging.go
// loggingMiddlewarePrivate is used for logging private api calls
// from internal services like alert manager
func loggingMiddlewarePrivate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
startTime := time.Now()
next.ServeHTTP(w, r)
zap.L().Info(path, zap.Duration("timeTaken", time.Since(startTime)), zap.String("path", path), zap.Bool("privatePort", true))
})
}

// TODO(remove): Implemented at pkg/http/middleware/logging.go
type loggingResponseWriter struct {
http.ResponseWriter
Expand Down
Loading