mirror of
https://github.com/lukaszraczylo/go-simple-graphql.git
synced 2026-10-12 00:45:31 +00:00
Update logging to the common logging format for all the projects.
This commit is contained in:
@@ -5,14 +5,12 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/logger"
|
||||
libpack_cache "github.com/lukaszraczylo/graphql-monitoring-proxy/cache"
|
||||
libpack_logging "github.com/lukaszraczylo/graphql-monitoring-proxy/logging"
|
||||
|
||||
"golang.org/x/net/http2"
|
||||
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/gookit/goutil/envutil"
|
||||
@@ -21,14 +19,8 @@ import (
|
||||
func NewConnection() *BaseClient {
|
||||
|
||||
b := &BaseClient{
|
||||
client: &http.Client{},
|
||||
MaxGoRoutines: -1,
|
||||
LoggingLevel: logger.Warn,
|
||||
LoggerColorful: true,
|
||||
}
|
||||
|
||||
if b.LoggerWriter == nil {
|
||||
b.LoggerWriter = log.New(os.Stdout, "", log.LstdFlags)
|
||||
client: &http.Client{},
|
||||
MaxGoRoutines: -1,
|
||||
}
|
||||
|
||||
b.endpoint = envutil.Getenv("GRAPHQL_ENDPOINT", "https://api.github.com/graphql")
|
||||
@@ -45,23 +37,7 @@ func NewConnection() *BaseClient {
|
||||
|
||||
b_tmp_log_level := envutil.Getenv("LOG_LEVEL", "info")
|
||||
|
||||
switch b_tmp_log_level {
|
||||
case "silent":
|
||||
b.LoggingLevel = logger.Silent
|
||||
case "error":
|
||||
b.LoggingLevel = logger.Error
|
||||
case "warn":
|
||||
b.LoggingLevel = logger.Warn
|
||||
case "info":
|
||||
b.LoggingLevel = logger.Info
|
||||
case "debug":
|
||||
b.LoggingLevel = logger.Debug
|
||||
}
|
||||
|
||||
b.Logger = NewLogger(b.LoggerWriter, logger.Config{
|
||||
Colorful: b.LoggerColorful,
|
||||
LogLevel: b.LoggingLevel,
|
||||
})
|
||||
b.Logger = libpack_logging.NewLogger()
|
||||
|
||||
var httpClient *http.Client
|
||||
|
||||
@@ -96,8 +72,8 @@ func NewConnection() *BaseClient {
|
||||
}
|
||||
b.client = httpClient
|
||||
|
||||
b.Logger.Debug(b, "graphQL client initialized;", "endpoint", b.endpoint, "responseType", b.responseType, "validate", b.validate, "cache", b.cache.enabled, "cacheTTL", b.cache.ttl, "maxGoRoutines", b.MaxGoRoutines, "loggingLevel", b_tmp_log_level, "loggerColorful", b.LoggerColorful)
|
||||
b.Logger.Info(b, "graphQL client initialized;")
|
||||
b.Logger.Debug("GraphQL client initialized", map[string]interface{}{"endpoint": b.endpoint, "responseType": b.responseType, "validate": b.validate, "cache": b.cache.enabled, "cacheTTL": b.cache.ttl, "maxGoRoutines": b.MaxGoRoutines, "loggingLevel": b_tmp_log_level})
|
||||
b.Logger.Info("GraphQL client initialized")
|
||||
return b
|
||||
}
|
||||
|
||||
@@ -119,6 +95,6 @@ func (b *BaseClient) enableCache() {
|
||||
}
|
||||
|
||||
func (b *BaseClient) disableCache() {
|
||||
b.Logger.Debug(b, "Disabling cache")
|
||||
b.Logger.Debug("Disabling cache")
|
||||
b.cache.enabled = false
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/logger"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -60,71 +59,6 @@ func TestNewConnection(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewConnectionLogLevels(t *testing.T) {
|
||||
tests := []struct {
|
||||
want *BaseClient
|
||||
name string
|
||||
env string
|
||||
}{
|
||||
{
|
||||
name: "Test NewConnection with log level set to debug",
|
||||
env: "debug",
|
||||
want: &BaseClient{
|
||||
endpoint: "https://api.github.com/graphql",
|
||||
responseType: "string",
|
||||
LoggingLevel: logger.Debug,
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: "Test NewConnection with log level set to info",
|
||||
env: "info",
|
||||
want: &BaseClient{
|
||||
endpoint: "https://api.github.com/graphql",
|
||||
responseType: "string",
|
||||
LoggingLevel: logger.Info,
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: "Test NewConnection with log level set to warn",
|
||||
env: "warn",
|
||||
want: &BaseClient{
|
||||
endpoint: "https://api.github.com/graphql",
|
||||
responseType: "string",
|
||||
LoggingLevel: logger.Warn,
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: "Test NewConnection with log level set to error",
|
||||
env: "error",
|
||||
want: &BaseClient{
|
||||
endpoint: "https://api.github.com/graphql",
|
||||
responseType: "string",
|
||||
LoggingLevel: logger.Error,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// temporarily set GRAPHQL_ENDPOINT env variable to https://api.github.com/graphql
|
||||
// and GRAPHQL_OUTPUT to string
|
||||
current := os.Getenv("GRAPHQL_ENDPOINT")
|
||||
defer os.Setenv("GRAPHQL_ENDPOINT", current)
|
||||
os.Setenv("GRAPHQL_ENDPOINT", "https://api.github.com/graphql")
|
||||
current_log_level := os.Getenv("LOG_LEVEL")
|
||||
defer os.Setenv("LOG_LEVEL", current_log_level)
|
||||
os.Setenv("LOG_LEVEL", tt.env)
|
||||
|
||||
got := NewConnection()
|
||||
assert.Equal(t, tt.want.endpoint, got.endpoint)
|
||||
assert.Equal(t, tt.want.responseType, got.responseType)
|
||||
assert.Equal(t, tt.want.LoggingLevel, got.LoggingLevel)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseClient_SetEndpoint(t *testing.T) {
|
||||
type fields struct {
|
||||
}
|
||||
|
||||
@@ -4,11 +4,11 @@ func (c *BaseClient) cacheLookup(hash string) []byte {
|
||||
if c.cache.client != nil {
|
||||
obj, found := c.cache.client.Get(hash)
|
||||
if found {
|
||||
c.Logger.Debug(c, "Cache hit;", "hash", hash)
|
||||
c.Logger.Debug("Cache hit", map[string]interface{}{"hash": hash})
|
||||
return obj
|
||||
}
|
||||
// if error is not nil it means that hash is not present in cache
|
||||
c.Logger.Debug(c, "Cache miss;", "hash", hash)
|
||||
c.Logger.Debug("Cache miss", map[string]interface{}{"hash": hash})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ go 1.21
|
||||
|
||||
require (
|
||||
github.com/avast/retry-go/v4 v4.5.0
|
||||
github.com/gookit/goutil v0.6.13
|
||||
github.com/gookit/goutil v0.6.14
|
||||
github.com/json-iterator/go v1.1.12
|
||||
github.com/lukaszraczylo/graphql-monitoring-proxy v0.5.3
|
||||
github.com/lukaszraczylo/graphql-monitoring-proxy v0.5.23
|
||||
github.com/stretchr/testify v1.8.4
|
||||
golang.org/x/net v0.17.0
|
||||
)
|
||||
@@ -15,9 +15,12 @@ require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/gookit/color v1.5.4 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/rs/zerolog v1.31.0 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
golang.org/x/sync v0.4.0 // indirect
|
||||
golang.org/x/sys v0.13.0 // indirect
|
||||
|
||||
@@ -1,31 +1,45 @@
|
||||
github.com/avast/retry-go/v4 v4.5.0 h1:QoRAZZ90cj5oni2Lsgl2GW8mNTnUCnmpx/iKpwVisHg=
|
||||
github.com/avast/retry-go/v4 v4.5.0/go.mod h1:7hLEXp0oku2Nir2xBAsg0PTphp9z71bN5Aq1fboC3+I=
|
||||
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
|
||||
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
|
||||
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
|
||||
github.com/gookit/goutil v0.6.13 h1:ttg7yMda6Q9fkE4P+YTwozd2wH1Le0CQldTAtOFBr7o=
|
||||
github.com/gookit/goutil v0.6.13/go.mod h1:YyDBddefmjS+mU2PDPgCcjVzTDM5WgExiDv5ZA/b8I8=
|
||||
github.com/gookit/goutil v0.6.14 h1:96elyOG4BvVoDaiT7vx1vHPrVyEtFfYlPPBODR0/FGQ=
|
||||
github.com/gookit/goutil v0.6.14/go.mod h1:YyDBddefmjS+mU2PDPgCcjVzTDM5WgExiDv5ZA/b8I8=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/lukaszraczylo/graphql-monitoring-proxy v0.5.3 h1:0BVn4/PyKDzo8XkZ4AGUBn7Fvg+ZU2zKAerQlUp9usY=
|
||||
github.com/lukaszraczylo/graphql-monitoring-proxy v0.5.3/go.mod h1:AHNrWWwe1LsfrknP8CLZlRn0E0GQX9Jak4pmY1FUlZ0=
|
||||
github.com/lukaszraczylo/graphql-monitoring-proxy v0.5.23 h1:MKrrnlXqqcsdlXyJ00CDZQOis7nTtoNMInM5P0VAhks=
|
||||
github.com/lukaszraczylo/graphql-monitoring-proxy v0.5.23/go.mod h1:81HTNAtartVlKdlSplx1dl1cSQbWYkxSOIYjNFjtVnI=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
|
||||
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
|
||||
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/rs/zerolog v1.31.0 h1:FcTR3NnLWW+NnTwwhFWiJSZr4ECLpqCm6QsEnyvbV4A=
|
||||
github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
@@ -38,6 +52,9 @@ golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
|
||||
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
||||
golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ=
|
||||
golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
|
||||
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek=
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/logger"
|
||||
|
||||
"github.com/gookit/goutil/timex"
|
||||
)
|
||||
|
||||
func NewLogger(writer Writer, config logger.Config) Logger {
|
||||
colorfulPrint := "%s[%s]%s %%s %%s"
|
||||
closeColor, debugColor, infoColor, warnColor, errorColor := "\033[0m", "\033[1;34m", "\033[1;32m", "\033[1;33m", "\033[1;31m"
|
||||
if !config.Colorful {
|
||||
closeColor, debugColor, infoColor, warnColor, errorColor = "", "", "", "", ""
|
||||
}
|
||||
debugStr := fmt.Sprintf(colorfulPrint, debugColor, "DEBUG", closeColor)
|
||||
infoStr := fmt.Sprintf(colorfulPrint, infoColor, "INFO", closeColor)
|
||||
warnStr := fmt.Sprintf(colorfulPrint, warnColor, "WARN", closeColor)
|
||||
errStr := fmt.Sprintf(colorfulPrint, errorColor, "ERROR", closeColor)
|
||||
|
||||
return &logging{
|
||||
Writer: writer,
|
||||
Config: config,
|
||||
infoStr: infoStr,
|
||||
warnStr: warnStr,
|
||||
errStr: errStr,
|
||||
debugStr: debugStr,
|
||||
}
|
||||
}
|
||||
|
||||
func setDate() string {
|
||||
tx := time.Now()
|
||||
return timex.DateFormat(tx, "Y-m-d H:I:S")
|
||||
}
|
||||
|
||||
func (l logging) Debug(client *BaseClient, msg string, data ...any) {
|
||||
if l.LogLevel >= logger.Debug {
|
||||
t := setDate()
|
||||
msg, data = censorSensitiveInfo(client, msg, data...)
|
||||
if client != nil {
|
||||
l.Printf(l.debugStr, fmt.Sprintf("[%s] %s", t, msg), sprint(data...))
|
||||
} else {
|
||||
l.Printf(l.debugStr, msg, sprint(data...))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (l logging) Info(client *BaseClient, msg string, data ...any) {
|
||||
if l.LogLevel >= logger.Info {
|
||||
t := setDate()
|
||||
msg, data = censorSensitiveInfo(client, msg, data...)
|
||||
if client != nil {
|
||||
l.Printf(l.infoStr, fmt.Sprintf("[%s] %s", t, msg), sprint(data...))
|
||||
} else {
|
||||
l.Printf(l.infoStr, msg, sprint(data...))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (l logging) Warn(client *BaseClient, msg string, data ...any) {
|
||||
if l.LogLevel >= logger.Warn {
|
||||
t := setDate()
|
||||
msg, data = censorSensitiveInfo(client, msg, data...)
|
||||
if client != nil {
|
||||
l.Printf(l.warnStr, fmt.Sprintf("[%s] %s", t, msg), sprint(data...))
|
||||
} else {
|
||||
l.Printf(l.warnStr, msg, sprint(data...))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (l logging) Error(client *BaseClient, msg string, data ...any) {
|
||||
if l.LogLevel >= logger.Error {
|
||||
t := setDate()
|
||||
msg, data = censorSensitiveInfo(client, msg, data...)
|
||||
if client != nil {
|
||||
l.Printf(l.errStr, fmt.Sprintf("[%s] %s", t, msg), sprint(data...))
|
||||
} else {
|
||||
l.Printf(l.errStr, msg, sprint(data...))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Logger interface {
|
||||
Debug(*BaseClient, string, ...any)
|
||||
Info(*BaseClient, string, ...any)
|
||||
Warn(*BaseClient, string, ...any)
|
||||
Error(*BaseClient, string, ...any)
|
||||
}
|
||||
|
||||
type Writer interface {
|
||||
Printf(string, ...any)
|
||||
}
|
||||
|
||||
type logging struct {
|
||||
Writer
|
||||
debugStr string
|
||||
infoStr string
|
||||
warnStr string
|
||||
errStr string
|
||||
logger.Config
|
||||
}
|
||||
|
||||
func censorSensitiveInfo(client *BaseClient, a string, b ...any) (string, []any) {
|
||||
// if client == nil || client.Token == "" {
|
||||
// return a, b
|
||||
// }
|
||||
// tokenFixed := strings.Split(client.Token, ":")[1]
|
||||
// for t := range b {
|
||||
// if b[t] != nil {
|
||||
// rV := reflect.TypeOf(b[t]).Kind()
|
||||
// if rV == reflect.String {
|
||||
// b[t] = strings.ReplaceAll(b[t].(string), tokenFixed, strings.Repeat("X", len(tokenFixed)))
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// a = strings.ReplaceAll(a, tokenFixed, strings.Repeat("X", len(tokenFixed)))
|
||||
// return a, b
|
||||
return a, b
|
||||
}
|
||||
|
||||
func sprint(a ...any) string {
|
||||
for t := range a {
|
||||
if a[t] != nil {
|
||||
rV := reflect.TypeOf(a[t]).Kind()
|
||||
if rV == reflect.Ptr {
|
||||
a[t] = reflect.ValueOf(a[t]).Elem().Interface()
|
||||
}
|
||||
rV = reflect.TypeOf(a[t]).Kind()
|
||||
if rV == reflect.Struct || rV == reflect.Map || rV == reflect.Slice {
|
||||
a[t], _ = logger.Serialize(a[t])
|
||||
}
|
||||
}
|
||||
}
|
||||
r := fmt.Sprintln(a...)
|
||||
r = r[:len(r)-1]
|
||||
return r
|
||||
}
|
||||
@@ -16,7 +16,7 @@ var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
func (c *BaseClient) convertToJson(v any) []byte {
|
||||
json, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
c.Logger.Error(c, "Can't convert to json;", "error", err.Error())
|
||||
c.Logger.Error("Can't convert to json;", map[string]interface{}{"error": err.Error()})
|
||||
return nil
|
||||
}
|
||||
return json
|
||||
@@ -43,7 +43,7 @@ func (c *BaseClient) NewQuery(q ...any) *Query {
|
||||
Variables: query.variables,
|
||||
})
|
||||
|
||||
c.Logger.Debug(c, "Clearing previously prepared variables and query")
|
||||
c.Logger.Debug("Clearing previously prepared variables and query")
|
||||
query.variables = nil
|
||||
|
||||
if query.context == nil {
|
||||
@@ -51,11 +51,11 @@ func (c *BaseClient) NewQuery(q ...any) *Query {
|
||||
}
|
||||
|
||||
if c.validate {
|
||||
c.Logger.Warn(c, "Validating query is not active")
|
||||
c.Logger.Warning("Validating query is active")
|
||||
}
|
||||
|
||||
query.query = ""
|
||||
c.Logger.Debug(c, "Query prepared;", "query", helpers.BytesToString(query.compiledQuery))
|
||||
c.Logger.Debug("Query prepared", map[string]interface{}{"query": query.compiledQuery})
|
||||
|
||||
return query
|
||||
}
|
||||
@@ -115,7 +115,7 @@ func (c *BaseClient) decodeResponse(jsonData []byte) any {
|
||||
var response map[string]interface{}
|
||||
err := json.Unmarshal(jsonData, &response)
|
||||
if err != nil {
|
||||
c.Logger.Error(c, "Error while converting to map[string]interface{};", "error", err.Error())
|
||||
c.Logger.Error("Error while converting to map[string]interface{};", map[string]interface{}{"error": err.Error()})
|
||||
return nil
|
||||
}
|
||||
return response
|
||||
@@ -124,7 +124,7 @@ func (c *BaseClient) decodeResponse(jsonData []byte) any {
|
||||
case "byte":
|
||||
return jsonData
|
||||
default:
|
||||
c.Logger.Error(c, "Unknown response type", "response", c.responseType)
|
||||
c.Logger.Error("Unknown response type", map[string]interface{}{"response": c.responseType})
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
+10
-10
@@ -14,7 +14,7 @@ func (c *BaseClient) executeQuery(query []byte, headers any) (result any, err er
|
||||
var queryResult queryResults
|
||||
httpRequest, err := http.NewRequest("POST", c.endpoint, bytes.NewBuffer(query))
|
||||
if err != nil {
|
||||
c.Logger.Error(c, "Error while creating http request;", "error", err.Error())
|
||||
c.Logger.Error("Error while creating http request;", map[string]interface{}{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ func (c *BaseClient) executeQuery(query []byte, headers any) (result any, err er
|
||||
func() error {
|
||||
httpResponse, err = c.client.Do(httpRequest)
|
||||
if err != nil {
|
||||
c.Logger.Error(c, "Error while executing http request;", "error", err.Error())
|
||||
c.Logger.Error("Error while executing http request;", map[string]interface{}{"error": err.Error()})
|
||||
return err
|
||||
}
|
||||
defer io.Copy(io.Discard, httpResponse.Body) // equivalent to `cp body /dev/null`
|
||||
@@ -45,20 +45,20 @@ func (c *BaseClient) executeQuery(query []byte, headers any) (result any, err er
|
||||
|
||||
body, err := io.ReadAll(httpResponse.Body)
|
||||
if err != nil {
|
||||
c.Logger.Error(c, "Error while reading http response;", "error", err.Error())
|
||||
c.Logger.Error("Error while reading http response;", map[string]interface{}{"error": err.Error()})
|
||||
return err
|
||||
}
|
||||
|
||||
err = json.Unmarshal(body, &queryResult)
|
||||
if err != nil {
|
||||
c.Logger.Error(c, "Error while unmarshalling http response;", "error", err.Error())
|
||||
c.Logger.Error("Error while unmarshalling http response;", map[string]interface{}{"error": err.Error()})
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.OnRetry(func(n uint, err error) {
|
||||
c.Logger.Error(c, "Retrying query", "error", err.Error())
|
||||
c.Logger.Error("Retrying query", map[string]interface{}{"error": err.Error()})
|
||||
}),
|
||||
retry.Attempts(uint(retries_available)),
|
||||
retry.DelayType(retry.BackOffDelay),
|
||||
@@ -76,29 +76,29 @@ func (q *queryExecutor) execute() {
|
||||
if q.should_cache {
|
||||
cachedResponse := q.client.cacheLookup(q.hash)
|
||||
if cachedResponse != nil {
|
||||
q.client.Logger.Debug(q.client, "Found cached response")
|
||||
q.client.Logger.Debug("Found cached response", map[string]interface{}{"hash": q.hash})
|
||||
q.result.data = q.client.decodeResponse(cachedResponse)
|
||||
return // return cached response
|
||||
} else {
|
||||
q.client.Logger.Debug(q.client, "No cached response found")
|
||||
q.client.Logger.Debug("Cache miss", map[string]interface{}{"hash": q.hash})
|
||||
}
|
||||
}
|
||||
|
||||
if q.retries_enabled {
|
||||
q.client.Logger.Debug(q.client, "Retries enabled")
|
||||
q.client.Logger.Debug("Retries enabled")
|
||||
q.client.retries.enabled = true
|
||||
}
|
||||
|
||||
response, err := q.client.executeQuery(q.query, q.headers)
|
||||
if err != nil {
|
||||
q.client.Logger.Error(q.client, "Error while executing query;", "error", err.Error())
|
||||
q.client.Logger.Error("Error while executing query;", map[string]interface{}{"error": err.Error()})
|
||||
q.result.errors = err
|
||||
return
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
q.client.Logger.Error(q.client, "Error while converting to json;", "error", err.Error())
|
||||
q.client.Logger.Error("Error while converting to json;", map[string]interface{}{"error": err.Error()})
|
||||
q.result.errors = err
|
||||
return
|
||||
}
|
||||
|
||||
+9
-12
@@ -4,8 +4,8 @@ import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/lukaszraczylo/go-simple-graphql/utils/logger"
|
||||
libpack_cache "github.com/lukaszraczylo/graphql-monitoring-proxy/cache"
|
||||
libpack_logging "github.com/lukaszraczylo/graphql-monitoring-proxy/logging"
|
||||
)
|
||||
|
||||
type cacheStore struct {
|
||||
@@ -21,17 +21,14 @@ type retriesConfig struct {
|
||||
}
|
||||
|
||||
type BaseClient struct {
|
||||
Logger Logger
|
||||
LoggerWriter Writer
|
||||
client *http.Client
|
||||
endpoint string
|
||||
responseType string
|
||||
cache cacheStore
|
||||
MaxGoRoutines int
|
||||
LoggingLevel logger.LogLevel
|
||||
LoggerColorful bool
|
||||
validate bool
|
||||
retries retriesConfig
|
||||
Logger *libpack_logging.LogConfig
|
||||
client *http.Client
|
||||
endpoint string
|
||||
responseType string
|
||||
cache cacheStore
|
||||
MaxGoRoutines int
|
||||
validate bool
|
||||
retries retriesConfig
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
const (
|
||||
reset = "\033[0m"
|
||||
redBold = "\033[1;31m"
|
||||
greenBold = "\033[1;32m"
|
||||
yellowBold = "\033[1;33m"
|
||||
blueBold = "\033[1;34m"
|
||||
)
|
||||
|
||||
type LogLevel int
|
||||
|
||||
const (
|
||||
Silent LogLevel = iota
|
||||
Error
|
||||
Warn
|
||||
Info
|
||||
Debug
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Colorful bool
|
||||
LogLevel LogLevel
|
||||
}
|
||||
|
||||
func Serialize(v interface{}) ([]byte, error) {
|
||||
b, err := json.Marshal(internalSerialize(v))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func internalSerialize(v interface{}) interface{} {
|
||||
if v != nil {
|
||||
switch reflect.TypeOf(v).Kind() {
|
||||
case reflect.Struct:
|
||||
r := make(map[string]interface{})
|
||||
name := reflect.TypeOf(v).Name()
|
||||
if name != "" {
|
||||
r["_"] = reflect.TypeOf(v).String()
|
||||
}
|
||||
for i := 0; i < reflect.ValueOf(v).NumField(); i++ {
|
||||
r[reflect.TypeOf(v).Field(i).Name] = internalSerialize(reflect.ValueOf(v).Field(i).Interface())
|
||||
}
|
||||
return r
|
||||
case reflect.Ptr:
|
||||
if !reflect.ValueOf(v).IsNil() {
|
||||
return internalSerialize(reflect.ValueOf(v).Elem().Interface())
|
||||
}
|
||||
case reflect.Slice:
|
||||
var r []interface{}
|
||||
tmpSlice := reflect.ValueOf(v)
|
||||
for i := 0; i < tmpSlice.Len(); i++ {
|
||||
r = append(r, internalSerialize(tmpSlice.Index(i).Interface()))
|
||||
}
|
||||
return r
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package logger
|
||||
|
||||
import "testing"
|
||||
|
||||
type Person struct {
|
||||
Name string
|
||||
Age int
|
||||
}
|
||||
|
||||
func TestSerializeStruct(t *testing.T) {
|
||||
person := Person{Name: "Alice", Age: 30}
|
||||
expected := `{"_":"logger.Person","Name":"Alice","Age":30}`
|
||||
actual, err := Serialize(person)
|
||||
if err != nil {
|
||||
t.Errorf("Error: %v", err)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Errorf("Expected: %v\nActual: %v", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerializeNilPointer(t *testing.T) {
|
||||
var person *Person
|
||||
expected := `null`
|
||||
actual, err := Serialize(person)
|
||||
if err != nil {
|
||||
t.Errorf("Error: %v", err)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Errorf("Expected: %v\nActual: %v", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerializeNonNilPointer(t *testing.T) {
|
||||
person := &Person{Name: "Alice", Age: 30}
|
||||
expected := `{"_":"logger.Person","Name":"Alice","Age":30}`
|
||||
actual, err := Serialize(person)
|
||||
if err != nil {
|
||||
t.Errorf("Error: %v", err)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Errorf("Expected: %v\nActual: %v", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerializeSlice(t *testing.T) {
|
||||
people := []Person{
|
||||
{Name: "Alice", Age: 30},
|
||||
{Name: "Bob", Age: 40},
|
||||
}
|
||||
expected := `[{"_":"logger.Person","Name":"Alice","Age":30},{"_":"logger.Person","Name":"Bob","Age":40}]`
|
||||
actual, err := Serialize(people)
|
||||
if err != nil {
|
||||
t.Errorf("Error: %v", err)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Errorf("Expected: %v\nActual: %v", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerializeSliceOfPointers(t *testing.T) {
|
||||
people := []*Person{
|
||||
{Name: "Alice", Age: 30},
|
||||
{Name: "Bob", Age: 40},
|
||||
}
|
||||
expected := `[{"_":"logger.Person","Name":"Alice","Age":30},{"_":"logger.Person","Name":"Bob","Age":40}]`
|
||||
|
||||
actual, err := Serialize(people)
|
||||
if err != nil {
|
||||
t.Errorf("Error: %v", err)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Errorf("Expected: %v\nActual: %v", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerializeUnsupportedType(t *testing.T) {
|
||||
type UnsupportedType chan int
|
||||
unsupportedType := make(UnsupportedType)
|
||||
_, err := Serialize(unsupportedType)
|
||||
if err == nil {
|
||||
t.Errorf("Expected an error, but got nil")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user