From 36ed0d75859f61cbe3f73729c2d91b3ad4755015 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Quentin=20Guid=C3=A9e?= Date: Sat, 9 Sep 2023 01:11:11 -0400 Subject: [PATCH] Use vertex-logger (vlog) package --- go.mod | 10 +- go.sum | 22 ++-- init.go | 20 ++-- pkg/ginutils/logger.go | 40 ++++--- pkg/log/log.go | 9 ++ pkg/logger/logger.go | 209 --------------------------------- pkg/storage/storage.go | 29 ++--- repository/instance_fs.go | 33 +++--- repository/instance_logs_fs.go | 12 +- repository/package_fs.go | 4 +- repository/proxy_fs.go | 17 +-- repository/runner_docker.go | 64 +++++----- repository/runner_fs.go | 15 +-- repository/service_fs.go | 4 +- repository/settings_fs.go | 15 +-- router/instance.go | 8 +- router/instances.go | 6 +- router/packages.go | 28 +++-- router/router.go | 14 +-- services/instance.go | 39 +++--- services/notifications.go | 4 +- services/proxy.go | 15 +-- services/update.go | 38 +++--- 23 files changed, 242 insertions(+), 413 deletions(-) create mode 100644 pkg/log/log.go delete mode 100644 pkg/logger/logger.go diff --git a/go.mod b/go.mod index 5fceb1fb..8dbdbf73 100644 --- a/go.mod +++ b/go.mod @@ -7,18 +7,18 @@ require ( github.com/disgoorg/disgo v0.16.9 github.com/docker/docker v23.0.3+incompatible github.com/docker/go-connections v0.4.0 - github.com/fatih/color v1.14.1 github.com/gin-contrib/cors v1.4.0 github.com/gin-contrib/sse v0.1.0 github.com/gin-contrib/static v0.0.1 github.com/gin-gonic/gin v1.9.0 - github.com/go-co-op/gocron v1.23.0 + github.com/go-co-op/gocron v1.33.1 github.com/go-git/go-git/v5 v5.6.1 github.com/google/go-github/v50 v50.0.0 - github.com/google/uuid v1.3.0 + github.com/google/uuid v1.3.1 github.com/pkg/errors v0.9.1 - github.com/stretchr/testify v1.8.2 + github.com/stretchr/testify v1.8.4 github.com/vertex-center/vertex-core-golang v0.0.0-20230423023245-a01db2466031 + github.com/vertex-center/vlog v1.0.1 golang.org/x/exp v0.0.0-20230801115018-d63ba01acd4b gopkg.in/yaml.v2 v2.4.0 ) @@ -38,6 +38,7 @@ require ( github.com/docker/distribution v2.8.2+incompatible // indirect github.com/docker/go-units v0.5.0 // indirect github.com/emirpasic/gods v1.18.1 // indirect + github.com/fatih/color v1.15.0 // indirect github.com/go-git/gcfg v1.5.0 // indirect github.com/go-git/go-billy/v5 v5.4.1 // indirect github.com/go-playground/locales v0.14.1 // indirect @@ -77,6 +78,7 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.9 // indirect github.com/xanzy/ssh-agent v0.3.3 // indirect + go.uber.org/atomic v1.9.0 // indirect golang.org/x/arch v0.1.0 // indirect golang.org/x/crypto v0.12.0 // indirect golang.org/x/mod v0.11.0 // indirect diff --git a/go.sum b/go.sum index 4e8c330e..8d3215cf 100644 --- a/go.sum +++ b/go.sum @@ -47,8 +47,8 @@ github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4 github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= -github.com/fatih/color v1.14.1 h1:qfhVLaG5s+nCROl1zJsZRxFeYrHLqWroPOQ8BWiNb4w= -github.com/fatih/color v1.14.1/go.mod h1:2oHN61fhTpgcxD3TSWCgKDiH1+x4OiDVVGH8WlgGZGg= +github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= +github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/gin-contrib/cors v1.4.0 h1:oJ6gwtUl3lqV0WEIwM/LxPF1QZ5qe2lGWdY2+bz7y0g= github.com/gin-contrib/cors v1.4.0/go.mod h1:bs9pNM0x/UsmHPBWT2xZz9ROh8xYjYkiURUfmBoMlcs= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= @@ -61,8 +61,8 @@ github.com/gin-gonic/gin v1.9.0 h1:OjyFBKICoexlu99ctXNR2gg+c5pKrKMuyjgARg9qeY8= github.com/gin-gonic/gin v1.9.0/go.mod h1:W1Me9+hsUSyj3CePGrd1/QrKJMSJ1Tu/0hFEH89961k= github.com/gliderlabs/ssh v0.3.5 h1:OcaySEmAQJgyYcArR+gGGTHCyE7nvhEMTlYY+Dp8CpY= github.com/gliderlabs/ssh v0.3.5/go.mod h1:8XB4KraRrX39qHhT6yxPsHedjA08I/uBVwj4xC+/+z4= -github.com/go-co-op/gocron v1.23.0 h1:cD8PCSsa88HKJSC8XhSWATSEKdgfKjrlnDu8zX+Jce4= -github.com/go-co-op/gocron v1.23.0/go.mod h1:gEQbrsoOV+HAp59D3LmYFgENQDeYp2QHsHT8N/Wzs/U= +github.com/go-co-op/gocron v1.33.1 h1:wjX+Dg6Ae29a/f9BSQjY1Rl+jflTpW9aDyMqseCj78c= +github.com/go-co-op/gocron v1.33.1/go.mod h1:NLi+bkm4rRSy1F8U7iacZOz0xPseMoIOnvabGoSe/no= github.com/go-git/gcfg v1.5.0 h1:Q5ViNfGF8zFgyJWPqYwA7qGFoMTEiBmdlkcfRmpIMa4= github.com/go-git/gcfg v1.5.0/go.mod h1:5m20vg6GwYabIxaOonVkTdrILxQMpEShl1xiMF4ua+E= github.com/go-git/go-billy/v5 v5.3.1/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= @@ -105,8 +105,8 @@ github.com/google/go-github/v50 v50.0.0/go.mod h1:Ev4Tre8QoKiolvbpOSG3FIi4Mlon3S github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= -github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= +github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= @@ -178,8 +178,9 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= +github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b h1:qYTY2tN72LhgDj2rtWG+LI6TXFl2ygFQQ4YezfVaGQE= github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b/go.mod h1:/pA7k3zsXKdjjAiUhB5CjuKib9KJGCaLvZwtxGC8U0s= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= @@ -201,8 +202,9 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= @@ -213,11 +215,15 @@ github.com/ugorji/go/codec v1.2.9 h1:rmenucSohSTiyL09Y+l2OCk+FrMxGMzho2+tjr5ticU github.com/ugorji/go/codec v1.2.9/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= github.com/vertex-center/vertex-core-golang v0.0.0-20230423023245-a01db2466031 h1:og0cF2u0K3n9628dEwi6QM5u5AcPwO4XKgp9ndHlfb0= github.com/vertex-center/vertex-core-golang v0.0.0-20230423023245-a01db2466031/go.mod h1:LW8yo6JkIKZxVJKhgbLsf1CAocMWnDYz1luF04juh/g= +github.com/vertex-center/vlog v1.0.1 h1:fa2bBD1h4T3+KNQ5jphuQ/Fb9eRj1uC28n/xYBFubRw= +github.com/vertex-center/vlog v1.0.1/go.mod h1:M52swDkdWWu3VWY2Cj+mqc64Nzx33sDukAgrQ3HA95c= github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/arch v0.1.0 h1:oMxhUYsO9VsR1dcoVUjJjIGhx1LXol3989T/yZ59Xsw= golang.org/x/arch v0.1.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= diff --git a/init.go b/init.go index 192c5aac..872f7e73 100644 --- a/init.go +++ b/init.go @@ -8,10 +8,11 @@ import ( "runtime" "github.com/vertex-center/vertex/config" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/router" "github.com/vertex-center/vertex/services" "github.com/vertex-center/vertex/types" + "github.com/vertex-center/vlog" ) // version, commit and date will be overridden by goreleaser @@ -22,22 +23,21 @@ var ( ) func main() { - logger.CreateDefaultLogger() - defer logger.DefaultLogger.CloseLogFiles() + defer log.Default.Close() - logger.Log("Vertex starting...").Print() + log.Default.Info("Vertex starting...") parseArgs() err := setupDependencies() if err != nil { - logger.Error(fmt.Errorf("failed to setup dependencies: %v", err)).Print() + log.Default.Error(fmt.Errorf("failed to setup dependencies: %v", err)) return } err = config.Current.Apply() if err != nil { - logger.Error(fmt.Errorf("failed to apply the current configuration: %v", err)).Print() + log.Default.Error(fmt.Errorf("failed to apply the current configuration: %v", err)) return } @@ -54,9 +54,9 @@ func main() { // Logs url := fmt.Sprintf("http://%s", config.Current.Host) fmt.Printf("\n-- Vertex Client :: %s\n\n", url) - logger.Log("Vertex started"). - AddKeyValue("url", url). - Print() + log.Default.Info("Vertex started", + vlog.String("url", url), + ) router.Start(fmt.Sprintf(":%s", config.Current.Port)) } @@ -98,7 +98,7 @@ func setupDependencies() error { for _, dep := range dependencies { err := setupDependency(dep) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) os.Exit(1) } } diff --git a/pkg/ginutils/logger.go b/pkg/ginutils/logger.go index 537382ab..816ab3a7 100644 --- a/pkg/ginutils/logger.go +++ b/pkg/ginutils/logger.go @@ -1,30 +1,36 @@ package ginutils import ( - "strings" - "github.com/gin-gonic/gin" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" + "github.com/vertex-center/vlog" ) func Logger(router string) gin.HandlerFunc { return gin.LoggerWithFormatter(func(params gin.LogFormatterParams) string { - l := logger.Request(). - AddKeyValue("router", router). - AddKeyValue("method", params.Method). - AddKeyValue("status", params.StatusCode). - AddKeyValue("path", params.Path). - AddKeyValue("latency", params.Latency). - AddKeyValue("ip", params.ClientIP). - AddKeyValue("size", params.BodySize) - if params.ErrorMessage != "" { - err, _ := strings.CutSuffix(params.ErrorMessage, "\n") - l.AddKeyValue("error", err) + log.Default.Request("request", + vlog.String("router", router), + vlog.String("method", params.Method), + vlog.Int("status", params.StatusCode), + vlog.String("path", params.Path), + vlog.String("latency", params.Latency.String()), + vlog.String("ip", params.ClientIP), + vlog.Int("size", params.BodySize), + vlog.String("error", params.ErrorMessage), + ) + } else { + log.Default.Request("request", + vlog.String("router", router), + vlog.String("method", params.Method), + vlog.Int("status", params.StatusCode), + vlog.String("path", params.Path), + vlog.String("latency", params.Latency.String()), + vlog.String("ip", params.ClientIP), + vlog.Int("size", params.BodySize), + ) } - l.PrintInExternalFiles() - - return l.String() + return "" }) } diff --git a/pkg/log/log.go b/pkg/log/log.go new file mode 100644 index 00000000..0a042262 --- /dev/null +++ b/pkg/log/log.go @@ -0,0 +1,9 @@ +package log + +import "github.com/vertex-center/vlog" + +var Default = *vlog.New( + vlog.WithOutputStd(), + vlog.WithOutputFile("live/logs", vlog.LogFormatText), + vlog.WithOutputFile("live/logs", vlog.LogFormatJson), +) diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go deleted file mode 100644 index 562a2bf7..00000000 --- a/pkg/logger/logger.go +++ /dev/null @@ -1,209 +0,0 @@ -package logger - -import ( - "encoding/json" - "fmt" - "os" - "path" - "strings" - "time" - - "github.com/fatih/color" - "github.com/go-co-op/gocron" -) - -var ( - DefaultLogger Logger - - LogKindOut = "out" - LogKindErr = "err" - - tagInfo = "INF" - tagWarn = "WRN" - tagError = "ERR" - tagRequest = "REQ" - - logsPath = path.Join("live", "logs") -) - -type Logger struct { - out *os.File - err *os.File - - text *os.File - json *os.File -} - -type Line struct { - logger *Logger - tag string - kind string - color color.Attribute - date string - messageColored string - messagePlain string - json map[string]any -} - -func CreateDefaultLogger() { - DefaultLogger = Logger{ - out: os.Stdout, - err: os.Stderr, - } - - DefaultLogger.OpenLogFiles() - DefaultLogger.StartCron() -} - -func (l *Logger) StartCron() { - s := gocron.NewScheduler(time.Local) - _, err := s.Every(1).Day().At("00:00").Do(func() { - l.CloseLogFiles() - l.OpenLogFiles() - }) - if err != nil { - _, _ = fmt.Fprint(os.Stderr, err.Error()) - return - } - s.StartAsync() -} - -func (l *Logger) CloseLogFiles() { - l.text.Close() - l.json.Close() -} - -func (l *Logger) OpenLogFiles() { - _ = os.MkdirAll(logsPath, os.ModePerm) - - filename := fmt.Sprintf("vertex_logs_%s.txt", time.Now().Format(time.DateOnly)) - t, err := os.OpenFile(path.Join(logsPath, filename), os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm) - if err != nil { - _, _ = fmt.Fprintf(os.Stderr, "failed to open %s: %v\n", filename, err) - t = nil - } - l.text = t - - // jsonl stands for the json lines format. https://jsonlines.org/ - filename = fmt.Sprintf("vertex_logs_%s.jsonl", time.Now().Format(time.DateOnly)) - j, err := os.OpenFile(path.Join(logsPath, filename), os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm) - if err != nil { - _, _ = fmt.Fprintf(os.Stderr, "failed to open %s: %v\n", filename, err) - j = nil - } - l.json = j -} - -func (l *Logger) Date() string { - return time.Now().Format(time.DateTime) -} - -func Log(message string) *Line { - return DefaultLogger.Log(message) -} - -func Request() *Line { - return DefaultLogger.Request() -} - -func Warn(message string) *Line { - return DefaultLogger.Warn(message) -} - -func Error(err error) *Line { - return DefaultLogger.Error(err) -} - -func (l *Logger) NewLine(tag string, kind string, color color.Attribute, message string) *Line { - messageColored := "" - messagePlain := "" - - if message != "" { - messageColored = formattedKeyValue(color, "msg", message) - messagePlain = "msg=" + message + " " - } - - return &Line{ - logger: l, - tag: tag, - kind: kind, - color: color, - date: l.Date(), - messageColored: messageColored, - messagePlain: messagePlain, - json: map[string]any{ - "seconds": time.Now().Unix(), - "nanoseconds": time.Now().UnixNano(), - "kind": tag, - "msg": message, - }, - } -} - -func (l *Logger) Log(message string) *Line { - return l.NewLine(tagInfo, LogKindOut, color.FgBlue, message) -} - -func (l *Logger) Request() *Line { - return l.NewLine(tagRequest, LogKindOut, color.FgGreen, "") -} - -func (l *Logger) Warn(message string) *Line { - return l.NewLine(tagWarn, LogKindOut, color.FgYellow, message) -} - -func (l *Logger) Error(err error) *Line { - return l.NewLine(tagError, LogKindErr, color.FgRed, err.Error()) -} - -func (l *Line) AddKeyValue(key string, value any) *Line { - l.messageColored += formattedKeyValue(l.color, key, value) - l.messagePlain += fmt.Sprintf("%s=%v ", key, value) - l.json[key] = value - return l -} - -func (l *Line) String() string { - return fmt.Sprintf("%s %s %s\n", - color.New(color.FgHiWhite).Sprintf(l.date), - color.New(l.color).Sprintf(l.tag), - strings.TrimSpace(l.messageColored), - ) -} - -func (l *Line) StringPlain() string { - return fmt.Sprintf("%s %s %s\n", l.date, l.tag, strings.TrimSpace(l.messagePlain)) -} - -func (l *Line) Json() string { - j, err := json.Marshal(l.json) - if err != nil { - return "" - } - return string(j) + "\n" -} - -func (l *Line) Print() { - if l.kind == LogKindErr { - _, _ = fmt.Fprint(l.logger.err, l.String()) - } else { - _, _ = fmt.Fprint(l.logger.out, l.String()) - } - l.PrintInExternalFiles() -} - -func (l *Line) PrintInExternalFiles() { - if l.logger.text != nil { - _, _ = fmt.Fprint(l.logger.text, l.StringPlain()) - } - if l.logger.json != nil { - _, _ = fmt.Fprint(l.logger.json, l.Json()) - } -} - -func formattedKeyValue(clr color.Attribute, key string, value any) string { - message := color.New(clr).Sprintf("%s=", key) - message += fmt.Sprintf("%v ", value) - - return message -} diff --git a/pkg/storage/storage.go b/pkg/storage/storage.go index 4d6c08d0..ffb4c45c 100644 --- a/pkg/storage/storage.go +++ b/pkg/storage/storage.go @@ -15,7 +15,8 @@ import ( "github.com/go-git/go-git/v5" "github.com/google/go-github/v50/github" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" + "github.com/vertex-center/vlog" ) const Path = "live" @@ -26,9 +27,9 @@ var ( ) func CloneOrPullRepository(url string, dest string) error { - logger.Log("downloading repository"). - AddKeyValue("url", url). - Print() + log.Default.Info("downloading repository", + vlog.String("url", url), + ) _, err := git.PlainClone(dest, false, &git.CloneOptions{ URL: url, @@ -58,10 +59,10 @@ func CloneOrPullRepository(url string, dest string) error { } func DownloadLatestGithubRelease(owner string, repo string, dest string) error { - logger.Log("downloading repository"). - AddKeyValue("owner", owner). - AddKeyValue("repo", repo). - Print() + log.Default.Info("downloading repository", + vlog.String("owner", owner), + vlog.String("repo", repo), + ) client := github.NewClient(nil) @@ -74,9 +75,9 @@ func DownloadLatestGithubRelease(owner string, repo string, dest string) error { } func DownloadGithubRelease(release *github.RepositoryRelease, dest string) error { - logger.Log("downloading GitHub release"). - AddKeyValue("release", *release.Name). - Print() + log.Default.Info("downloading repository", + vlog.String("release", *release.Name), + ) platform := fmt.Sprintf("%s_%s", runtime.GOOS, runtime.GOARCH) @@ -107,9 +108,9 @@ func DownloadGithubRelease(release *github.RepositoryRelease, dest string) error } func Download(url string, dest string, filename string) error { - logger.Log("downloading repository"). - AddKeyValue("url", url). - Print() + log.Default.Info("downloading repository", + vlog.String("url", url), + ) err := os.MkdirAll(dest, os.ModePerm) if err != nil { diff --git a/repository/instance_fs.go b/repository/instance_fs.go index 17532eff..4fdc796c 100644 --- a/repository/instance_fs.go +++ b/repository/instance_fs.go @@ -5,15 +5,15 @@ import ( "encoding/json" "errors" "fmt" - "log" "os" "path" "strings" "github.com/google/uuid" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/pkg/storage" "github.com/vertex-center/vertex/types" + "github.com/vertex-center/vlog" "gopkg.in/yaml.v2" ) @@ -36,10 +36,10 @@ func NewInstanceFSRepository() InstanceFSRepository { err := os.MkdirAll(r.instancesPath, os.ModePerm) if err != nil && !os.IsExist(err) { - logger.Error(err). - AddKeyValue("message", "failed to create directory"). - AddKeyValue("path", r.instancesPath). - Print() + log.Default.Error(err, + vlog.String("message", "failed to create directory"), + vlog.String("path", r.instancesPath), + ) os.Exit(1) } @@ -108,7 +108,7 @@ func (r *InstanceFSRepository) LoadSettings(i *types.Instance) error { settingsBytes, err := os.ReadFile(settingsPath) if errors.Is(err, os.ErrNotExist) { - logger.Log("instance_settings.json not found. using default.").Print() + log.Default.Warn("instance_settings.json not found. using default.") } else if err != nil { return err } else { @@ -124,9 +124,9 @@ func (r *InstanceFSRepository) LoadSettings(i *types.Instance) error { func (r *InstanceFSRepository) ReadService(instancePath string) (types.Service, error) { data, err := os.ReadFile(path.Join(instancePath, ".vertex", "service.yml")) if err != nil { - logger.Warn("'.vertex/service.yml' file not found"). - AddKeyValue("path", path.Dir(instancePath)). - Print() + log.Default.Warn("'.vertex/service.yml' file not found", + vlog.String("path", path.Dir(instancePath)), + ) } var service types.Service @@ -182,26 +182,27 @@ func (r *InstanceFSRepository) LoadEnv(i *types.Instance) error { func (r *InstanceFSRepository) Reload(load func(uuid uuid.UUID)) { entries, err := os.ReadDir(r.instancesPath) if err != nil { - log.Fatal(err) + log.Default.Error(err) + os.Exit(1) } for _, entry := range entries { info, err := entry.Info() if err != nil { - logger.Error(err).Print() + log.Default.Error(err) continue } isInstance := entry.IsDir() || info.Mode()&os.ModeSymlink != 0 if isInstance { - logger.Log("found service"). - AddKeyValue("uuid", entry.Name()). - Print() + log.Default.Info("found instance", + vlog.String("uuid", entry.Name()), + ) id, err := uuid.Parse(entry.Name()) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) continue } diff --git a/repository/instance_logs_fs.go b/repository/instance_logs_fs.go index 2cdab6f7..710a3fd3 100644 --- a/repository/instance_logs_fs.go +++ b/repository/instance_logs_fs.go @@ -9,7 +9,7 @@ import ( "github.com/go-co-op/gocron" "github.com/google/uuid" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/pkg/storage" "github.com/vertex-center/vertex/types" ) @@ -75,7 +75,7 @@ func (r *InstanceLogsFSRepository) Close(uuid uuid.UUID) error { func (r *InstanceLogsFSRepository) Push(uuid uuid.UUID, line types.LogLine) { l, err := r.getLogger(uuid) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) return } l.currentLine += 1 @@ -86,7 +86,7 @@ func (r *InstanceLogsFSRepository) Push(uuid uuid.UUID, line types.LogLine) { _, err = fmt.Fprintf(l.file, "%s\n", line.Message) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) } } @@ -127,17 +127,17 @@ func (r *InstanceLogsFSRepository) startCron() { for id := range r.loggers { err := r.Close(id) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) continue } err = r.Open(id) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) } } }) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) return } s.StartAsync() diff --git a/repository/package_fs.go b/repository/package_fs.go index b13815d1..e19a3884 100644 --- a/repository/package_fs.go +++ b/repository/package_fs.go @@ -8,7 +8,7 @@ import ( "sync" "github.com/pkg/errors" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/pkg/storage" "github.com/vertex-center/vertex/types" ) @@ -45,7 +45,7 @@ func NewPackageFSRepository(params *PackageRepositoryParams) PackageFSRepository err := repo.Reload() if err != nil { - logger.Error(fmt.Errorf("failed to reload services repository: %v", err)).Print() + log.Default.Error(fmt.Errorf("failed to reload services repository: %v", err)) } return repo } diff --git a/repository/proxy_fs.go b/repository/proxy_fs.go index 4132916e..684ac47d 100644 --- a/repository/proxy_fs.go +++ b/repository/proxy_fs.go @@ -7,9 +7,10 @@ import ( "path" "github.com/google/uuid" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/pkg/storage" "github.com/vertex-center/vertex/types" + "github.com/vertex-center/vlog" ) type ProxyFSRepository struct { @@ -31,10 +32,10 @@ func NewProxyFSRepository(params *ProxyRepositoryParams) ProxyFSRepository { err := os.MkdirAll(params.proxyPath, os.ModePerm) if err != nil && !os.IsExist(err) { - logger.Error(err). - AddKeyValue("message", "failed to create directory"). - AddKeyValue("path", params.proxyPath). - Print() + log.Default.Error(err, + vlog.String("message", "failed to create directory"), + vlog.String("path", params.proxyPath), + ) os.Exit(1) } @@ -66,15 +67,15 @@ func (r *ProxyFSRepository) read() { file, err := os.ReadFile(p) if errors.Is(err, os.ErrNotExist) { - logger.Log("redirects.json doesn't exists or could not be found").Print() + log.Default.Info("redirects.json doesn't exists or could not be found") } else if err != nil { - logger.Error(err).Print() + log.Default.Error(err) return } err = json.Unmarshal(file, &r.redirects) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) return } } diff --git a/repository/runner_docker.go b/repository/runner_docker.go index 89853463..88eafd71 100644 --- a/repository/runner_docker.go +++ b/repository/runner_docker.go @@ -15,9 +15,10 @@ import ( "github.com/docker/docker/client" "github.com/docker/docker/pkg/archive" "github.com/docker/go-connections/nat" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/pkg/storage" "github.com/vertex-center/vertex/types" + "github.com/vertex-center/vlog" ) type RunnerDockerRepository struct { @@ -31,9 +32,9 @@ type dockerMessage struct { func NewRunnerDockerRepository() RunnerDockerRepository { cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { - logger.Warn("couldn't connect with the Docker cli."). - AddKeyValue("error", err.Error()). - Print() + log.Default.Warn("couldn't connect with the Docker cli.", + vlog.String("error", err.Error()), + ) return RunnerDockerRepository{} } @@ -79,9 +80,9 @@ func (r RunnerDockerRepository) Start(instance *types.Instance, onLog func(msg s if errors.Is(err, ErrContainerNotFound) { containerName := instance.DockerContainerName() - logger.Log("container doesn't exists, create it."). - AddKeyValue("container_name", containerName). - Print() + log.Default.Info("container doesn't exists, create it.", + vlog.String("container_name", containerName), + ) options := createContainerOptions{ imageName: imageName, @@ -227,10 +228,14 @@ func (r RunnerDockerRepository) CheckForUpdates(instance *types.Instance) error } if latestImageID == currentImageID { - logger.Log("already up-to-date").AddKeyValue("uuid", instance.UUID).Print() + log.Default.Info("already up-to-date", + vlog.String("uuid", instance.UUID.String()), + ) instance.Update = nil } else { - logger.Log("a new update is available").AddKeyValue("uuid", instance.UUID).Print() + log.Default.Info("a new update is available", + vlog.String("uuid", instance.UUID.String()), + ) instance.Update = &types.InstanceUpdate{ CurrentVersion: currentImageID, LatestVersion: latestImageID, @@ -339,9 +344,9 @@ func (r RunnerDockerRepository) buildImageFromDockerfile(instancePath string, im msg := dockerMessage{} err := json.Unmarshal(scanner.Bytes(), &msg) if err != nil { - logger.Warn("Failed to parse message:"). - AddKeyValue("msg", scanner.Text()). - Print() + log.Default.Warn("Failed to parse message", + vlog.String("message", scanner.Text()), + ) } else { if msg.Stream != "" { onMsg(msg.Stream) @@ -349,7 +354,7 @@ func (r RunnerDockerRepository) buildImageFromDockerfile(instancePath string, im } } - logger.Log("Docker build: success.").Print() + log.Default.Info("Docker build: success.") return nil } @@ -383,9 +388,9 @@ func (r RunnerDockerRepository) createContainer(options createContainerOptions) res, err := r.cli.ContainerCreate(context.Background(), &config, &hostConfig, nil, nil, options.containerName) for _, warn := range res.Warnings { - logger.Warn("warning while creating container"). - AddKeyValue("warning", warn). - Print() + log.Default.Warn("warning while creating container", + vlog.String("warning", warn), + ) } return res.ID, err } @@ -397,16 +402,15 @@ func (r RunnerDockerRepository) watchForStatusChange(containerID string, instanc select { case err := <-errChan: if err != nil { - logger.Error(err). - AddKeyValue("uuid", instance.UUID). - Print() + log.Default.Error(err, + vlog.String("uuid", instance.UUID.String()), + ) } case status := <-resChan: - logger.Log("docker container exited with status"). - AddKeyValue("uuid", instance.UUID). - AddKeyValue("status", status.StatusCode). - Print() - + log.Default.Info("container exited", + vlog.String("uuid", instance.UUID.String()), + vlog.Int64("status", status.StatusCode), + ) setStatus(types.InstanceStatusOff) } }() @@ -422,9 +426,9 @@ func (r RunnerDockerRepository) watchForLogs(containerID string, instance *types Tail: "0", }) if err != nil { - logger.Error(err). - AddKeyValue("uuid", instance.UUID). - Print() + log.Default.Error(err, + vlog.String("uuid", instance.UUID.String()), + ) } scanner := bufio.NewScanner(logs) @@ -432,9 +436,9 @@ func (r RunnerDockerRepository) watchForLogs(containerID string, instance *types onLog(scanner.Text()) } _ = logs.Close() - logger.Log("logs pipe closed"). - AddKeyValue("uuid", instance.UUID). - Print() + log.Default.Info("logs pipe closed", + vlog.String("uuid", instance.UUID.String()), + ) }() } diff --git a/repository/runner_fs.go b/repository/runner_fs.go index 30f5d30e..25c7b955 100644 --- a/repository/runner_fs.go +++ b/repository/runner_fs.go @@ -9,9 +9,10 @@ import ( "path" "github.com/google/uuid" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/pkg/storage" "github.com/vertex-center/vertex/types" + "github.com/vertex-center/vlog" ) type RunnerFSRepository struct { @@ -30,9 +31,9 @@ func (r RunnerFSRepository) Delete(instance *types.Instance) error { func (r RunnerFSRepository) Start(instance *types.Instance, onLog func(msg string), onErr func(msg string), setStatus func(status string)) error { if r.commands[instance.UUID] != nil { - logger.Error(errors.New("runner already started")). - AddKeyValue("name", instance.Name). - Print() + log.Default.Error(errors.New("runner already started"), + vlog.String("name", instance.Name), + ) } dir := r.getPath(*instance) @@ -101,9 +102,9 @@ func (r RunnerFSRepository) Start(instance *types.Instance, onLog func(msg strin go func() { err := cmd.Wait() if err != nil { - logger.Error(err). - AddKeyValue("name", instance.Service.Name). - Print() + log.Default.Error(err, + vlog.String("name", instance.Service.Name), + ) } setStatus(types.InstanceStatusOff) }() diff --git a/repository/service_fs.go b/repository/service_fs.go index 7790e420..0e361c57 100644 --- a/repository/service_fs.go +++ b/repository/service_fs.go @@ -6,7 +6,7 @@ import ( "os" "path" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/pkg/storage" "github.com/vertex-center/vertex/types" "gopkg.in/yaml.v2" @@ -34,7 +34,7 @@ func NewServiceFSRepository(params *ServiceRepositoryParams) ServiceFSRepository } err := repo.Reload() if err != nil { - logger.Error(fmt.Errorf("failed to reload services repository: %v", err)).Print() + log.Default.Error(fmt.Errorf("failed to reload services repository: %v", err)) } return repo } diff --git a/repository/settings_fs.go b/repository/settings_fs.go index a6845e1e..2d59875e 100644 --- a/repository/settings_fs.go +++ b/repository/settings_fs.go @@ -6,9 +6,10 @@ import ( "os" "path" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/pkg/storage" "github.com/vertex-center/vertex/types" + "github.com/vertex-center/vlog" ) type SettingsFSRepository struct { @@ -30,10 +31,10 @@ func NewSettingsFSRepository(params *SettingsRepositoryParams) SettingsFSReposit err := os.MkdirAll(params.settingsPath, os.ModePerm) if err != nil && !os.IsExist(err) { - logger.Error(err). - AddKeyValue("message", "failed to create directory"). - AddKeyValue("path", params.settingsPath). - Print() + log.Default.Error(err, + vlog.String("message", "failed to create directory"), + vlog.String("path", params.settingsPath), + ) os.Exit(1) } @@ -43,7 +44,7 @@ func NewSettingsFSRepository(params *SettingsRepositoryParams) SettingsFSReposit err = repo.read() if err != nil { - logger.Error(err).Print() + log.Default.Error(err) } return repo @@ -73,7 +74,7 @@ func (r *SettingsFSRepository) read() error { file, err := os.ReadFile(p) if errors.Is(err, os.ErrNotExist) { - logger.Log("settings.json doesn't exists or could not be found").Print() + log.Default.Info("settings.json doesn't exists or could not be found") return nil } else if err != nil { return err diff --git a/router/instance.go b/router/instance.go index dca72fac..8e0f1afb 100644 --- a/router/instance.go +++ b/router/instance.go @@ -9,7 +9,7 @@ import ( "github.com/gin-contrib/sse" "github.com/gin-gonic/gin" "github.com/google/uuid" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/types" ) @@ -207,7 +207,7 @@ func handleInstanceEvents(c *gin.Context) { }) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) return false } first = false @@ -218,7 +218,7 @@ func handleInstanceEvents(c *gin.Context) { case e := <-eventsChan: err := sse.Encode(w, e) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) } return true case <-done: @@ -240,7 +240,7 @@ func handleGetDependencies(c *gin.Context) { for name := range *i.Methods.Script.Dependencies { dep, err := packageService.GetByID(name) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) continue } deps[name] = dep diff --git a/router/instances.go b/router/instances.go index 70c322b2..ac1e6e17 100644 --- a/router/instances.go +++ b/router/instances.go @@ -6,7 +6,7 @@ import ( "github.com/gin-contrib/sse" "github.com/gin-gonic/gin" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/types" ) @@ -58,7 +58,7 @@ func handleInstancesEvents(c *gin.Context) { }) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) return false } first = false @@ -69,7 +69,7 @@ func handleInstancesEvents(c *gin.Context) { case e := <-eventsChan: err := sse.Encode(w, e) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) } return true case <-done: diff --git a/router/packages.go b/router/packages.go index f3709edc..a65f37cf 100644 --- a/router/packages.go +++ b/router/packages.go @@ -6,7 +6,8 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" + "github.com/vertex-center/vlog" ) func addPackagesRoutes(r *gin.RouterGroup) { @@ -31,19 +32,22 @@ func handleInstallPackages(c *gin.Context) { for _, d := range body.Packages { pkg, err := packageService.GetByID(d.Name) if err != nil { - logger.Warn("dependency not found"). - AddKeyValue("name", d.Name). - AddKeyValue("package_manager", d.PackageManager). - Print() + log.Default.Warn("dependency not found", + vlog.String("name", d.Name), + vlog.String("package_manager", d.PackageManager), + ) continue } - logger.Log(fmt.Sprintf("installing package name='%s' with package_manager=%s", d.Name, d.PackageManager)).Print() + log.Default.Info("installing package", + vlog.String("name", d.Name), + vlog.String("package_manager", d.PackageManager), + ) cmd, err := packageService.InstallationCommand(&pkg, d.PackageManager) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) continue } @@ -55,15 +59,15 @@ func handleInstallPackages(c *gin.Context) { } else { err = packageService.Install(cmd) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) continue } } - logger.Log("package installed successfully"). - AddKeyValue("name", d.Name). - AddKeyValue("package_manager", d.PackageManager). - Print() + log.Default.Info("package installed successfully", + vlog.String("name", d.Name), + vlog.String("package_manager", d.PackageManager), + ) c.Status(http.StatusOK) return diff --git a/router/router.go b/router/router.go index d33f5481..33198f36 100644 --- a/router/router.go +++ b/router/router.go @@ -14,7 +14,7 @@ import ( "github.com/gin-gonic/gin" "github.com/vertex-center/vertex-core-golang/router/middleware" "github.com/vertex-center/vertex/pkg/ginutils" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/pkg/storage" "github.com/vertex-center/vertex/repository" "github.com/vertex-center/vertex/services" @@ -100,7 +100,7 @@ func (r *Router) Start(addr string) { go func() { err := proxyService.Start() if err != nil { - logger.Error(err).Print() + log.Default.Error(err) return } @@ -116,14 +116,14 @@ func (r *Router) Start(addr string) { err := notificationsService.StartWebhook() if err != nil { - logger.Error(err).Print() + log.Default.Error(err) } err = r.server.ListenAndServe() if errors.Is(err, http.ErrServerClosed) { - logger.Log("Vertex closed").Print() + log.Default.Info("Vertex closed") } else if err != nil { - logger.Error(err).Print() + log.Default.Error(err) } } @@ -134,7 +134,7 @@ func (r *Router) Stop() { err := r.server.Shutdown(context.Background()) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) return } @@ -152,7 +152,7 @@ func (r *Router) handleSignals() { signal.Notify(c, os.Interrupt) go func() { <-c - logger.Log("shutdown signal sent").Print() + log.Default.Info("shutdown signal sent") r.Stop() os.Exit(0) }() diff --git a/services/instance.go b/services/instance.go index aa1b033b..7bab5eb0 100644 --- a/services/instance.go +++ b/services/instance.go @@ -11,9 +11,10 @@ import ( "github.com/antelman107/net-wait-go/wait" "github.com/go-git/go-git/v5" "github.com/google/uuid" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/pkg/storage" "github.com/vertex-center/vertex/types" + "github.com/vertex-center/vlog" "gopkg.in/yaml.v2" ) @@ -102,9 +103,9 @@ func (s *InstanceService) Start(uuid uuid.UUID) error { Message: "Starting instance...", }) - logger.Log("starting instance"). - AddKeyValue("uuid", uuid). - Print() + log.Default.Info("starting instance", + vlog.String("uuid", uuid.String()), + ) if instance.IsRunning() { s.eventsRepo.Send(types.EventInstanceLog{ @@ -150,9 +151,9 @@ func (s *InstanceService) Start(uuid uuid.UUID) error { Message: "Instance started.", }) - logger.Log("instance started"). - AddKeyValue("uuid", uuid). - Print() + log.Default.Info("instance started", + vlog.String("uuid", uuid.String()), + ) } return err @@ -176,17 +177,17 @@ func (s *InstanceService) StartAll() { return } - logger.Log("trying to ping Google...").Print() + log.Default.Info("trying to ping Google...") // Wait for internet connection if !wait.New( wait.WithWait(time.Second), wait.WithBreak(500*time.Millisecond), ).Do([]string{"google.com:80"}) { - logger.Error(errors.New("internet connection: Failed to ping google.com")).Print() + log.Default.Error(errors.New("internet connection: Failed to ping google.com")) return } else { - logger.Log("internet connection: OK").Print() + log.Default.Info("internet connection: OK") } // Start them @@ -194,7 +195,7 @@ func (s *InstanceService) StartAll() { go func(id uuid.UUID) { err := s.Start(id) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) } }(id) } @@ -212,9 +213,9 @@ func (s *InstanceService) Stop(uuid uuid.UUID) error { Message: "Stopping instance...", }) - logger.Log("stopping instance"). - AddKeyValue("uuid", uuid). - Print() + log.Default.Info("stopping instance", + vlog.String("uuid", uuid.String()), + ) if !instance.IsRunning() { s.eventsRepo.Send(types.EventInstanceLog{ @@ -240,9 +241,9 @@ func (s *InstanceService) Stop(uuid uuid.UUID) error { Message: "Instance stopped.", }) - logger.Log("instance stopped"). - AddKeyValue("uuid", uuid). - Print() + log.Default.Info("instance stopped", + vlog.String("uuid", uuid.String()), + ) s.setStatus(instance, types.InstanceStatusOff) } else { @@ -259,7 +260,7 @@ func (s *InstanceService) StopAll() { } err := s.Stop(i.UUID) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) } } } @@ -463,7 +464,7 @@ func (s *InstanceService) reload() { s.instanceRepo.Reload(func(uuid uuid.UUID) { err := s.load(uuid) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) return } }) diff --git a/services/notifications.go b/services/notifications.go index 006fd08e..1f9e302d 100644 --- a/services/notifications.go +++ b/services/notifications.go @@ -4,7 +4,7 @@ import ( "github.com/disgoorg/disgo/discord" "github.com/disgoorg/disgo/webhook" "github.com/google/uuid" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/types" ) @@ -71,7 +71,7 @@ func (s *NotificationsService) sendStatus(instanceUUID uuid.UUID, status string) instance, err := s.instanceRepo.Get(instanceUUID) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) return } diff --git a/services/proxy.go b/services/proxy.go index 5b29e9b0..c6b843bc 100644 --- a/services/proxy.go +++ b/services/proxy.go @@ -12,8 +12,9 @@ import ( "github.com/google/uuid" "github.com/vertex-center/vertex-core-golang/router/middleware" "github.com/vertex-center/vertex/pkg/ginutils" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/types" + "github.com/vertex-center/vlog" ) var ( @@ -52,7 +53,7 @@ func (s *ProxyService) Start() error { go func() { err := s.server.ListenAndServe() if err != nil && !errors.Is(err, http.ErrServerClosed) { - logger.Error(err).Print() + log.Default.Error(err) return } }() @@ -95,22 +96,22 @@ func (s *ProxyService) handleProxy(c *gin.Context) { } if redirect == nil { - logger.Warn("this host is not registered in the reverse proxy"). - AddKeyValue("host", host). - Print() + log.Default.Warn("this host is not registered in the reverse proxy", + vlog.String("host", host), + ) return } target, err := url.Parse(redirect.Target) if err != nil { - logger.Error(err).Print() + log.Default.Error(err) return } proxy := httputil.NewSingleHostReverseProxy(target) proxy.ErrorHandler = func(w http.ResponseWriter, request *http.Request, err error) { if err != nil && !errors.Is(err, context.Canceled) { - logger.Error(err).Print() + log.Default.Error(err) } } proxy.Director = func(request *http.Request) { diff --git a/services/update.go b/services/update.go index 298e1705..dab27664 100644 --- a/services/update.go +++ b/services/update.go @@ -15,9 +15,10 @@ import ( "github.com/go-git/go-git/v5" "github.com/google/go-github/v50/github" "github.com/vertex-center/vertex/config" - "github.com/vertex-center/vertex/pkg/logger" + "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/pkg/storage" "github.com/vertex-center/vertex/types" + "github.com/vertex-center/vlog" "golang.org/x/exp/slices" ) @@ -54,29 +55,28 @@ func (s *UpdateDependenciesService) GetCachedUpdates() types.Updates { } func (s *UpdateDependenciesService) CheckForUpdates() (types.Updates, error) { - logger.Log("fetching all updates...").Print() + log.Default.Info("fetching all updates...") s.updates.Items = []types.Update{} for _, dependency := range s.dependencies { - logger.Log("fetching dependency"). - AddKeyValue("id", dependency.GetID()). - Print() + log.Default.Info("fetching dependency", + vlog.String("id", dependency.GetID()), + ) update, err := dependency.CheckForUpdate() if err != nil { return types.Updates{}, err } if update != nil { - logger.Log("dependency needs update"). - AddKeyValue("id", dependency.GetID()). - Print() - + log.Default.Info("dependency needs update", + vlog.String("id", dependency.GetID()), + ) s.updates.Items = append(s.updates.Items, *update) } else { - logger.Log("dependency already up-to-date"). - AddKeyValue("id", dependency.GetID()). - Print() + log.Default.Info("dependency already up-to-date", + vlog.String("id", dependency.GetID()), + ) } } @@ -111,7 +111,7 @@ type vertexDependency struct { func (d *vertexDependency) CheckForUpdate() (*types.Update, error) { if d.currentVersion == "dev" { - logger.Log("skipping vertex update in 'dev' version").Print() + log.Default.Info("skipping vertex update in 'dev' version") return nil, nil } @@ -146,10 +146,10 @@ func (d *vertexDependency) CheckForUpdate() (*types.Update, error) { NeedsRestart: true, } - logger.Log("a new release for Vertex is available"). - AddKeyValue("current", d.currentVersion). - AddKeyValue("release", latestVersion). - Print() + log.Default.Info("a new release for Vertex is available", + vlog.String("current", d.currentVersion), + vlog.String("release", latestVersion), + ) return d.update, nil } @@ -180,7 +180,7 @@ func (d *vertexDependency) InstallUpdate() error { d.release = nil d.update = nil - logger.Warn("a new Vertex update has been installed. please restart Vertex to apply changes.").Print() + log.Default.Warn("a new Vertex update has been installed. please restart Vertex to apply changes.") return nil } @@ -231,7 +231,7 @@ func (d *VertexClientDependency) CheckForUpdate() (*types.Update, error) { } func (d *VertexClientDependency) InstallUpdate() error { - logger.Log("downloading vertex-webui client...").Print() + log.Default.Info("downloading vertex-webui client...") for _, asset := range d.release.Assets { if strings.Contains(*asset.Name, "vertex-webui") {