feat: add log level for better debugging

This commit is contained in:
Jonas Kaninda
2024-11-10 19:58:53 +01:00
parent 0d406e3256
commit bbaf47fa0c
13 changed files with 96 additions and 42 deletions

View File

@@ -102,9 +102,19 @@ func (GatewayServer) Config(configFile string) (*GatewayServer, error) {
middlewares: c.Middlewares,
}, nil
}
func GetConfigPaths() string {
return util.GetStringEnv("GOMAY_CONFIG_FILE", ConfigFile)
// SetEnv sets environment variables
func (gatewayServer GatewayServer) SetEnv() {
util.SetEnv("GOMA_LOG_LEVEL", gatewayServer.gateway.LogLevel)
util.SetEnv("GOMA_ERROR_LOG", gatewayServer.gateway.ErrorLog)
util.SetEnv("GOMA_ACCESS_LOG", gatewayServer.gateway.AccessLog)
}
func GetConfigPaths() string {
return util.GetStringEnv("GOMA_CONFIG_FILE", ConfigFile)
}
// InitConfig initializes configs
func InitConfig(cmd *cobra.Command) {
configFile, _ := cmd.Flags().GetString("output")
if configFile == "" {
@@ -114,6 +124,8 @@ func InitConfig(cmd *cobra.Command) {
return
}
// initConfig initializes configs
func initConfig(configFile string) {
if configFile == "" {
configFile = GetConfigPaths()

View File

@@ -65,7 +65,7 @@ func ProxyErrorHandler(w http.ResponseWriter, r *http.Request, err error) {
// HealthCheckHandler handles health check of routes
func (heathRoute HealthCheckRoute) HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
logger.Info("%s %s %s %s", r.Method, r.RemoteAddr, r.URL, r.UserAgent())
logger.Debug("%s %s %s %s", r.Method, r.RemoteAddr, r.URL, r.UserAgent())
wg := sync.WaitGroup{}
wg.Add(len(heathRoute.Routes))
var routes []HealthCheckRouteResponse
@@ -80,11 +80,11 @@ func (heathRoute HealthCheckRoute) HealthCheckHandler(w http.ResponseWriter, r *
}
routes = append(routes, HealthCheckRouteResponse{Name: route.Name, Status: "unhealthy", Error: "Error: " + err.Error()})
} else {
logger.Info("Route %s is healthy", route.Name)
logger.Debug("Route %s is healthy", route.Name)
routes = append(routes, HealthCheckRouteResponse{Name: route.Name, Status: "healthy", Error: ""})
}
} else {
logger.Warn("Route %s's healthCheck is undefined", route.Name)
logger.Debug("Route %s's healthCheck is undefined", route.Name)
routes = append(routes, HealthCheckRouteResponse{Name: route.Name, Status: "undefined", Error: ""})
}
}()

View File

@@ -46,7 +46,7 @@ func (intercept InterceptErrors) ErrorInterceptor(next http.Handler) http.Handle
rec := newResponseRecorder(w)
next.ServeHTTP(rec, r)
if canIntercept(rec.statusCode, intercept.Errors) {
logger.Error("Backend error")
logger.Debug("Backend error")
logger.Error("An error occurred from the backend with the status code: %d", rec.statusCode)
w.Header().Set("Content-Type", "application/json")
//Update Origin Cors Headers

View File

@@ -82,6 +82,7 @@ func (jwtAuth JwtAuth) AuthMiddleware(next http.Handler) http.Handler {
}
return
}
logger.Trace("JWT Auth response headers: %v", authReq.Header)
// Copy headers from the original request to the new request
for name, values := range r.Header {
for _, value := range values {
@@ -96,8 +97,8 @@ func (jwtAuth JwtAuth) AuthMiddleware(next http.Handler) http.Handler {
client := &http.Client{}
authResp, err := client.Do(authReq)
if err != nil || authResp.StatusCode != http.StatusOK {
logger.Info("%s %s %s %s", r.Method, getRealIP(r), r.URL, r.UserAgent())
logger.Warn("Proxy authentication error")
logger.Debug("%s %s %s %s", r.Method, getRealIP(r), r.URL, r.UserAgent())
logger.Debug("Proxy authentication error")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
err = json.NewEncoder(w).Encode(ProxyResponseError{
@@ -139,10 +140,11 @@ func (jwtAuth JwtAuth) AuthMiddleware(next http.Handler) http.Handler {
// AuthMiddleware checks for the Authorization header and verifies the credentials
func (basicAuth AuthBasic) AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Trace("Basic-Auth request headers: %v", r.Header)
// Get the Authorization header
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
logger.Error("Proxy error, missing Authorization header")
logger.Debug("Proxy error, missing Authorization header")
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
@@ -175,7 +177,7 @@ func (basicAuth AuthBasic) AuthMiddleware(next http.Handler) http.Handler {
// Decode the base64 encoded username:password string
payload, err := base64.StdEncoding.DecodeString(authHeader[len("Basic "):])
if err != nil {
logger.Error("Proxy error, missing Basic Authorization header")
logger.Debug("Proxy error, missing Basic Authorization header")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
err := json.NewEncoder(w).Encode(ProxyResponseError{

View File

@@ -66,7 +66,7 @@ func (rl *RateLimiter) RateLimitMiddleware() mux.MiddlewareFunc {
rl.mu.Unlock()
if client.RequestCount > rl.Requests {
logger.Error("Too many requests from IP: %s %s %s", clientID, r.URL, r.UserAgent())
logger.Debug("Too many requests from IP: %s %s %s", clientID, r.URL, r.UserAgent())
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
//Update Origin Cors Headers

View File

@@ -30,6 +30,8 @@ import (
func (proxyRoute ProxyRoute) ProxyHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
logger.Info("%s %s %s %s", r.Method, getRealIP(r), r.URL.Path, r.UserAgent())
logger.Trace("Request params: %s", r.URL.RawQuery)
logger.Trace("Request Headers: %s", r.Header)
// Check Method if is allowed
if len(proxyRoute.methods) > 0 {
if !slices.Contains(proxyRoute.methods, r.Method) {

View File

@@ -188,6 +188,7 @@ type Gateway struct {
BlockCommonExploits bool `yaml:"blockCommonExploits"`
AccessLog string `yaml:"accessLog" env:"GOMA_ACCESS_LOG, overwrite"`
ErrorLog string `yaml:"errorLog" env:"GOMA_ERROR_LOG=, overwrite"`
LogLevel string `yaml:"logLevel" env:"GOMA_LOG_LEVEL, overwrite"`
// DisableHealthCheckStatus enable and disable routes health check
DisableHealthCheckStatus bool `yaml:"disableHealthCheckStatus"`
// DisableRouteHealthCheckError allows enabling and disabling backend healthcheck errors