Merge pull request #150 from jkaninda/feature/logger

chore: improvement of logs for better logging
This commit is contained in:
2024-12-09 13:15:40 +01:00
committed by GitHub
29 changed files with 135 additions and 61 deletions

View File

@@ -21,7 +21,7 @@ import (
"fmt" "fmt"
"os" "os"
pkg "github.com/jkaninda/goma-gateway/internal" "github.com/jkaninda/goma-gateway/internal"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -34,7 +34,7 @@ var CheckConfigCmd = &cobra.Command{
fmt.Println("no config file specified") fmt.Println("no config file specified")
os.Exit(1) os.Exit(1)
} }
err := pkg.CheckConfig(configFile) err := internal.CheckConfig(configFile)
if err != nil { if err != nil {
fmt.Printf(" Error checking config file: %s\n", err) fmt.Printf(" Error checking config file: %s\n", err)
os.Exit(1) os.Exit(1)

View File

@@ -17,9 +17,9 @@ limitations under the License.
*/ */
import ( import (
"fmt" "fmt"
"github.com/jkaninda/goma-gateway/internal"
"os" "os"
pkg "github.com/jkaninda/goma-gateway/internal"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -41,7 +41,7 @@ var InitConfigCmd = &cobra.Command{
os.Exit(1) os.Exit(1)
} }
} }
err := pkg.InitConfig(configFile) err := internal.InitConfig(configFile)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)

View File

@@ -33,10 +33,10 @@ var ServerCmd = &cobra.Command{
intro() intro()
configFile, _ := cmd.Flags().GetString("config") configFile, _ := cmd.Flags().GetString("config")
if configFile == "" { if configFile == "" {
configFile = pkg.GetConfigPaths() configFile = internal.GetConfigPaths()
} }
ctx := context.Background() ctx := context.Background()
g := pkg.GatewayServer{} g := internal.GatewayServer{}
gs, err := g.Config(configFile, ctx) gs, err := g.Config(configFile, ctx)
if err != nil { if err != nil {
fmt.Printf("Could not load configuration: %v\n", err) fmt.Printf("Could not load configuration: %v\n", err)

1
go.sum
View File

@@ -28,6 +28,7 @@ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jedib0t/go-pretty/v6 v6.6.3 h1:nGqgS0tgIO1Hto47HSaaK4ac/I/Bu7usmdD3qvs0WvM= github.com/jedib0t/go-pretty/v6 v6.6.3 h1:nGqgS0tgIO1Hto47HSaaK4ac/I/Bu7usmdD3qvs0WvM=
github.com/jedib0t/go-pretty/v6 v6.6.3/go.mod h1:zbn98qrYlh95FIhwwsbIip0LYpwSG8SUOScs+v9/t0E= github.com/jedib0t/go-pretty/v6 v6.6.3/go.mod h1:zbn98qrYlh95FIhwwsbIip0LYpwSG8SUOScs+v9/t0E=
github.com/jinzhu/copier v0.4.0/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg=
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
import ( import (
"fmt" "fmt"

View File

@@ -1,4 +1,4 @@
package pkg package internal
/* /*
Copyright 2024 Jonas Kaninda Copyright 2024 Jonas Kaninda
@@ -191,7 +191,6 @@ func initConfig(configFile string) error {
Type: AccessMiddleware, Type: AccessMiddleware,
Paths: []string{ Paths: []string{
"/swagger-ui/*", "/swagger-ui/*",
"/v2/swagger-ui/*",
"/api-docs/*", "/api-docs/*",
"/actuator/*", "/actuator/*",
}, },

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
type Cors struct { type Cors struct {
// Cors Allowed origins, // Cors Allowed origins,

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
import ( import (
"fmt" "fmt"

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
// Gateway contains Goma Proxy Gateway's configs // Gateway contains Goma Proxy Gateway's configs
type Gateway struct { type Gateway struct {

View File

@@ -1,4 +1,4 @@
package pkg package internal
/* /*
Copyright 2024 Jonas Kaninda Copyright 2024 Jonas Kaninda

View File

@@ -1,4 +1,4 @@
package pkg package internal
/* /*
Copyright 2024 Jonas Kaninda Copyright 2024 Jonas Kaninda

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
import ( import (
"context" "context"

58
internal/helpers_test.go Normal file
View File

@@ -0,0 +1,58 @@
/*
* Copyright 2024 Jonas Kaninda
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package internal
import (
"fmt"
"testing"
)
func TestValidateIPAddress(t *testing.T) {
tests := []string{
"192.168.1.100",
"192.168.1.120",
}
for _, test := range tests {
if validateIPAddress(test) {
fmt.Println("Ip is valid")
} else {
fmt.Println("Ip is invalid")
}
}
}
func TestValidateIPOrCIDR(t *testing.T) {
tests := []string{
"192.168.1.100",
"192.168.1.100",
"192.168.1.100/32",
"invalid-input",
"192.168.1.100/33",
}
for _, test := range tests {
isIP, isCIDR := isIPOrCIDR(test)
if isIP {
fmt.Printf("%s is an IP address\n", test)
} else if isCIDR {
fmt.Printf("%s is a CIDR\n", test)
} else {
fmt.Printf("%s is neither an IP address nor a CIDR\n", test)
}
}
}

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
import ( import (
"github.com/golang-jwt/jwt" "github.com/golang-jwt/jwt"

View File

@@ -1,4 +1,4 @@
package pkg package internal
import ( import (
"errors" "errors"

View File

@@ -1,4 +1,4 @@
package pkg package internal
/* /*
Copyright 2024 Jonas Kaninda Copyright 2024 Jonas Kaninda

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
// Middleware defined the route middlewares // Middleware defined the route middlewares
type Middleware struct { type Middleware struct {

View File

@@ -1,4 +1,4 @@
package pkg package internal
/* /*
Copyright 2024 Jonas Kaninda Copyright 2024 Jonas Kaninda

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
import ( import (
"github.com/jkaninda/goma-gateway/internal/middlewares" "github.com/jkaninda/goma-gateway/internal/middlewares"

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
import ( import (
"fmt" "fmt"

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
// Route defines gateway route // Route defines gateway route
type Route struct { type Route struct {

View File

@@ -1,4 +1,4 @@
package pkg package internal
/* /*
Copyright 2024 Jonas Kaninda Copyright 2024 Jonas Kaninda
@@ -254,7 +254,6 @@ func attachMiddlewares(rIndex int, route Route, gateway Gateway, router *mux.Rou
logger.Error("Error: %v, middleware not applied", err.Error()) logger.Error("Error: %v, middleware not applied", err.Error())
} }
if len(accessPolicy.SourceRanges) != 0 { if len(accessPolicy.SourceRanges) != 0 {
logger.Info("Ips: %v", accessPolicy.SourceRanges)
access := middlewares.AccessPolicy{ access := middlewares.AccessPolicy{
SourceRanges: accessPolicy.SourceRanges, SourceRanges: accessPolicy.SourceRanges,
Action: accessPolicy.Action, Action: accessPolicy.Action,

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
import ( import (
"fmt" "fmt"

View File

@@ -1,4 +1,4 @@
package pkg package internal
/* /*
Copyright 2024 Jonas Kaninda Copyright 2024 Jonas Kaninda

View File

@@ -1,4 +1,4 @@
package pkg package internal
import ( import (
"context" "context"

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
import ( import (
"crypto/tls" "crypto/tls"

View File

@@ -15,7 +15,7 @@
* *
*/ */
package pkg package internal
import ( import (
"context" "context"

View File

@@ -1,4 +1,4 @@
package pkg package internal
const ConfigDir = "/etc/goma/" // Default configuration file const ConfigDir = "/etc/goma/" // Default configuration file
const ExtraDir = ConfigDir + "extra" const ExtraDir = ConfigDir + "extra"

View File

@@ -26,47 +26,62 @@ import (
"github.com/jkaninda/goma-gateway/util" "github.com/jkaninda/goma-gateway/util"
) )
// Info returns info log // Generic logging function
func Info(msg string, args ...interface{}) { func logMessage(level, defaultOutput, msg string, args ...interface{}) {
log.SetOutput(getStd(util.GetStringEnv("GOMA_ACCESS_LOG", "/dev/stdout"))) logLevel := getLogLevel()
logWithCaller("INFO", msg, args...) if shouldLog(level, logLevel) {
log.SetOutput(getStd(util.GetStringEnv("GOMA_ACCESS_LOG", defaultOutput)))
logWithCaller(level, msg, args...)
}
} }
// Warn returns warning log // Info logs informational messages
func Warn(msg string, args ...interface{}) { func Info(msg string, args ...interface{}) {
log.SetOutput(getStd(util.GetStringEnv("GOMA_ACCESS_LOG", "/dev/stdout"))) logMessage("INFO", "/dev/stdout", msg, args...)
logWithCaller("WARN", msg, args...) }
// Warn logs warning messages
func Warn(msg string, args ...interface{}) {
logMessage("WARN", "/dev/stdout", msg, args...)
} }
// Error logs error messages // Error logs error messages
func Error(msg string, args ...interface{}) { func Error(msg string, args ...interface{}) {
log.SetOutput(getStd(util.GetStringEnv("GOMA_ERROR_LOG", "/dev/stderr"))) logMessage("ERROR", "/dev/stderr", msg, args...)
logWithCaller("ERROR", msg, args...)
} }
// Fatal logs fatal errors and exits the program
func Fatal(msg string, args ...interface{}) { func Fatal(msg string, args ...interface{}) {
log.SetOutput(os.Stdout) log.SetOutput(os.Stdout)
logWithCaller("ERROR", msg, args...) logWithCaller("ERROR", msg, args...)
os.Exit(1) os.Exit(1)
} }
// Debug logs debug messages
func Debug(msg string, args ...interface{}) { func Debug(msg string, args ...interface{}) {
log.SetOutput(getStd(util.GetStringEnv("GOMA_ACCESS_LOG", "/dev/stdout"))) logMessage("DEBUG", "/dev/stdout", msg, args...)
logLevel := util.GetStringEnv("GOMA_LOG_LEVEL", "")
if strings.ToLower(logLevel) == traceLog || strings.ToLower(logLevel) == "debug" {
logWithCaller("DEBUG", msg, args...)
} }
} // Trace logs trace messages
func Trace(msg string, args ...interface{}) { func Trace(msg string, args ...interface{}) {
log.SetOutput(getStd(util.GetStringEnv("GOMA_ACCESS_LOG", "/dev/stdout"))) logMessage("TRACE", "/dev/stdout", msg, args...)
logLevel := util.GetStringEnv("GOMA_LOG_LEVEL", "")
if strings.ToLower(logLevel) == traceLog {
logWithCaller("DEBUG", msg, args...)
} }
// Determines whether the message should be logged based on log level
func shouldLog(level, currentLevel string) bool {
levelOrder := map[string]int{
"trace": 1,
"debug": 2,
"info": 3,
"warn": 4,
"error": 5,
"off": 6,
}
current := strings.ToLower(currentLevel)
target := strings.ToLower(level)
return levelOrder[target] >= levelOrder[current]
} }
// Helper function to format and log messages with file and line number // Helper function to format and log messages with file and line number
@@ -83,17 +98,15 @@ func logWithCaller(level, msg string, args ...interface{}) {
file = "unknown" file = "unknown"
line = 0 line = 0
} }
// Log message with caller information if GOMA_LOG_LEVEL is trace
logLevel := util.GetStringEnv("GOMA_LOG_LEVEL", "") if getLogLevel() == traceLog {
if strings.ToLower(logLevel) != "off" {
if strings.ToLower(logLevel) == traceLog {
log.Printf("%s: %s (File: %s, Line: %d)\n", level, formattedMessage, file, line) log.Printf("%s: %s (File: %s, Line: %d)\n", level, formattedMessage, file, line)
} else { } else {
log.Printf("%s: %s\n", level, formattedMessage) log.Printf("%s: %s\n", level, formattedMessage)
} }
} }
}
// Determines the appropriate standard output based on the environment variable
func getStd(out string) *os.File { func getStd(out string) *os.File {
switch out { switch out {
case "/dev/stdout": case "/dev/stdout":
@@ -104,6 +117,10 @@ func getStd(out string) *os.File {
return os.Stdin return os.Stdin
default: default:
return os.Stdout return os.Stdout
}
}
} // Retrieves the current log level from environment variables
func getLogLevel() string {
return strings.ToLower(util.GetStringEnv("GOMA_LOG_LEVEL", ""))
} }