refactor: enhancement of logging, config and metrics

This commit is contained in:
Jonas Kaninda
2024-11-11 08:50:34 +01:00
parent e25bc218b5
commit 11c72e5e17
12 changed files with 97 additions and 65 deletions

View File

@@ -21,7 +21,6 @@ import (
"fmt"
"github.com/jkaninda/goma-gateway/util"
"gopkg.in/yaml.v3"
"log"
"os"
)
@@ -46,21 +45,21 @@ func CheckConfig(fileName string) error {
}
for index, route := range gateway.gateway.Routes {
if len(route.Name) == 0 {
log.Printf("Warning: route name is empty, index: [%d]", index)
fmt.Printf("Warning: route name is empty, index: [%d]", index)
}
if route.Destination == "" && len(route.Backends) == 0 {
log.Printf("Error: no destination or backends specified for route: %s | index: [%d] \n", route.Name, index)
fmt.Printf("Error: no destination or backends specified for route: %s | index: [%d] \n", route.Name, index)
}
}
//Check middleware
for index, mid := range c.Middlewares {
if util.HasWhitespace(mid.Name) {
log.Printf("Warning: Middleware contains whitespace: %s | index: [%d], please remove whitespace characters\n", mid.Name, index)
fmt.Printf("Warning: Middleware contains whitespace: %s | index: [%d], please remove whitespace characters\n", mid.Name, index)
}
}
log.Printf("Routes count=%d Middlewares count=%d\n", len(gateway.gateway.Routes), len(gateway.middlewares))
fmt.Printf("Routes count=%d Middlewares count=%d\n", len(gateway.gateway.Routes), len(gateway.middlewares))
return nil

View File

@@ -20,7 +20,6 @@ import (
"github.com/jkaninda/goma-gateway/internal/middleware"
"github.com/jkaninda/goma-gateway/pkg/logger"
"github.com/jkaninda/goma-gateway/util"
"github.com/spf13/cobra"
"golang.org/x/oauth2"
"golang.org/x/oauth2/amazon"
"golang.org/x/oauth2/facebook"
@@ -83,7 +82,11 @@ func (GatewayServer) Config(configFile string) (*GatewayServer, error) {
return nil, err
}
}
initConfig(ConfigFile)
err := initConfig(ConfigFile)
if err != nil {
return nil, err
}
logger.Info("Generating new configuration file...done")
logger.Info("Server configuration file is available at %s", ConfigFile)
util.SetEnv("GOMA_CONFIG_FILE", ConfigFile)
buf, err := os.ReadFile(ConfigFile)
@@ -115,18 +118,13 @@ func GetConfigPaths() string {
}
// InitConfig initializes configs
func InitConfig(cmd *cobra.Command) {
configFile, _ := cmd.Flags().GetString("output")
if configFile == "" {
configFile = GetConfigPaths()
}
initConfig(configFile)
return
func InitConfig(configFile string) error {
return initConfig(configFile)
}
// initConfig initializes configs
func initConfig(configFile string) {
func initConfig(configFile string) error {
if configFile == "" {
configFile = GetConfigPaths()
}
@@ -292,13 +290,13 @@ func initConfig(configFile string) {
}
yamlData, err := yaml.Marshal(&conf)
if err != nil {
logger.Fatal("Error serializing configuration %v", err.Error())
return fmt.Errorf("serializing configuration %v\n", err.Error())
}
err = os.WriteFile(configFile, yamlData, 0644)
if err != nil {
logger.Fatal("Unable to write config file %s", err)
return fmt.Errorf("unable to write config file %s\n", err)
}
logger.Info("Configuration file has been initialized successfully")
return nil
}
func (Gateway) Setup(conf string) *Gateway {
if util.FileExists(conf) {

View File

@@ -27,7 +27,12 @@ func printRoute(routes []Route) {
t := table.NewWriter()
t.AppendHeader(table.Row{"Name", "Route", "Rewrite", "Destination"})
for _, route := range routes {
t.AppendRow(table.Row{route.Name, route.Path, route.Rewrite, route.Destination})
if len(route.Backends) > 0 {
t.AppendRow(table.Row{route.Name, route.Path, route.Rewrite, fmt.Sprintf("backends: [%d]", len(route.Backends))})
} else {
t.AppendRow(table.Row{route.Name, route.Path, route.Rewrite, route.Destination})
}
}
fmt.Println(t.Render())
}

View File

@@ -35,7 +35,7 @@ var totalRequests = prometheus.NewCounterVec(
Name: "http_requests_total",
Help: "Number of get requests.",
},
[]string{"path"},
[]string{"name", "path"},
)
var responseStatus = prometheus.NewCounterVec(
@@ -49,16 +49,19 @@ var responseStatus = prometheus.NewCounterVec(
var httpDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_response_time_seconds",
Help: "Duration of HTTP requests.",
}, []string{"path"})
}, []string{"name", "path"})
func prometheusMiddleware(next http.Handler) http.Handler {
func (pr PrometheusRoute) prometheusMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
timer := prometheus.NewTimer(httpDuration.WithLabelValues(path))
path := pr.path
if len(path) == 0 {
route := mux.CurrentRoute(r)
path, _ = route.GetPathTemplate()
}
timer := prometheus.NewTimer(httpDuration.WithLabelValues(pr.name, path))
responseStatus.WithLabelValues(strconv.Itoa(http.StatusOK)).Inc()
totalRequests.WithLabelValues(path).Inc()
totalRequests.WithLabelValues(pr.name, path).Inc()
timer.ObserveDuration()
next.ServeHTTP(w, r)

View File

@@ -43,9 +43,7 @@ func (gatewayServer GatewayServer) Initialize() *mux.Router {
if gateway.EnableMetrics {
// Prometheus endpoint
r.Path("/metrics").Handler(promhttp.Handler())
r.Use(prometheusMiddleware)
}
// Routes health check
if !gateway.DisableHealthCheckStatus {
r.HandleFunc("/healthz", heath.HealthCheckHandler).Methods("GET")
@@ -238,7 +236,14 @@ func (gatewayServer GatewayServer) Initialize() *mux.Router {
} else {
router.PathPrefix("").Handler(proxyRoute.ProxyHandler())
}
if gateway.EnableMetrics {
pr := PrometheusRoute{
name: route.Name,
path: route.Path,
}
// Prometheus endpoint
router.Use(pr.prometheusMiddleware)
}
} else {
logger.Error("Error, path is empty in route %s", route.Name)
logger.Error("Route path ignored: %s", route.Path)