From 6421902a4f5bde86e7f778b4404d97f8fcdba07b Mon Sep 17 00:00:00 2001 From: knqyf263 Date: Sat, 21 Oct 2023 15:50:36 +0900 Subject: [PATCH 1/2] refactor: replace logrus with slog Signed-off-by: knqyf263 --- cmd/scanner-trivy/main.go | 23 ++++++------ go.mod | 4 +-- go.sum | 9 +++++ pkg/etc/checker.go | 64 ++++++++++++++-------------------- pkg/etc/config.go | 23 +++++++----- pkg/etc/config_test.go | 28 +++++++-------- pkg/http/api/base_handler.go | 4 +-- pkg/http/api/server.go | 30 ++++++++-------- pkg/http/api/v1/handler.go | 40 +++++++++++---------- pkg/persistence/redis/store.go | 48 ++++++++++++------------- pkg/queue/enqueuer.go | 14 ++++---- pkg/queue/worker.go | 20 +++++------ pkg/redisx/pool.go | 15 ++++---- pkg/scan/controller.go | 10 +++--- pkg/scan/transformer.go | 11 +++--- pkg/trivy/wrapper.go | 40 ++++++++++----------- 16 files changed, 189 insertions(+), 194 deletions(-) diff --git a/cmd/scanner-trivy/main.go b/cmd/scanner-trivy/main.go index 75df1163..0f9ecd85 100644 --- a/cmd/scanner-trivy/main.go +++ b/cmd/scanner-trivy/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "log/slog" "os" "os/signal" "syscall" @@ -15,7 +16,6 @@ import ( "github.com/aquasecurity/harbor-scanner-trivy/pkg/redisx" "github.com/aquasecurity/harbor-scanner-trivy/pkg/scan" "github.com/aquasecurity/harbor-scanner-trivy/pkg/trivy" - log "github.com/sirupsen/logrus" ) var ( @@ -26,10 +26,10 @@ var ( ) func main() { - log.SetOutput(os.Stdout) - log.SetLevel(etc.GetLogLevel()) - log.SetReportCaller(false) - log.SetFormatter(&log.JSONFormatter{}) + logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ + Level: etc.LogLevel(), + })) + slog.SetDefault(logger) info := etc.BuildInfo{ Version: version, @@ -38,16 +38,15 @@ func main() { } if err := run(info); err != nil { - log.Fatalf("Error: %v", err) + slog.Error("Error: %v", err) + os.Exit(1) } } func run(info etc.BuildInfo) error { - log.WithFields(log.Fields{ - "version": info.Version, - "commit": info.Commit, - "built_at": info.Date, - }).Info("Starting harbor-scanner-trivy") + slog.Info("Starting harbor-scanner-trivy", slog.String("version", info.Version), + slog.String("commit", info.Commit), slog.String("built_at", info.Date), + ) config, err := etc.GetConfig() if err != nil { @@ -79,7 +78,7 @@ func run(info etc.BuildInfo) error { sigint := make(chan os.Signal, 1) signal.Notify(sigint, syscall.SIGINT, syscall.SIGTERM) captured := <-sigint - log.WithField("signal", captured.String()).Debug("Trapped os signal") + slog.Debug("Trapped os signal", slog.String("signal", captured.String())) apiServer.Shutdown() worker.Stop() diff --git a/go.mod b/go.mod index 3ddd82d9..3264731d 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/aquasecurity/harbor-scanner-trivy -go 1.20 +go 1.21 require ( github.com/FZambia/sentinel v1.1.1 @@ -12,7 +12,6 @@ require ( github.com/gorilla/mux v1.8.0 github.com/opencontainers/go-digest v1.0.0 github.com/prometheus/client_golang v1.17.0 - github.com/sirupsen/logrus v1.9.3 github.com/stretchr/testify v1.8.4 github.com/testcontainers/testcontainers-go v0.25.0 golang.org/x/net v0.17.0 @@ -55,6 +54,7 @@ require ( github.com/robfig/cron v1.2.0 // indirect github.com/shirou/gopsutil/v3 v3.23.8 // indirect github.com/shoenig/go-m1cpu v0.1.6 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect github.com/stretchr/objx v0.5.0 // indirect github.com/tklauser/go-sysconf v0.3.12 // indirect github.com/tklauser/numcpus v0.6.1 // indirect diff --git a/go.sum b/go.sum index 31a2586f..673c785e 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,7 @@ dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 h1:bvDV9vkmnHYOMsOr4WLk+Vo07yKIzd94sVoIqshQ4bU= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= @@ -28,6 +29,7 @@ github.com/cpuguy83/dockercfg v0.3.1 h1:/FpZ+JaygUR/lZP2NlFI2DVfrOEMAIKP5wWEJdoY github.com/cpuguy83/dockercfg v0.3.1/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= +github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/cyphar/filepath-securejoin v0.2.3/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4= 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= @@ -71,6 +73,7 @@ github.com/klauspost/compress v1.16.0 h1:iULayQNOReoYUe+1qtKOqw9CwJv3aNQu8ivo7lw github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= @@ -115,6 +118,7 @@ github.com/prometheus/procfs v0.11.1/go.mod h1:eesXgaPo1q7lBpVMoMy0ZOFTth9hBn4W/ github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ= github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/seccomp/libseccomp-golang v0.9.2-0.20220502022130-f33da4d89646/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg= github.com/shirou/gopsutil/v3 v3.23.8 h1:xnATPiybo6GgdRoC4YoGnxXZFRc3dqQTGi73oLvvBrE= @@ -172,6 +176,7 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= +golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -195,7 +200,9 @@ golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9sn golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= +golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= @@ -218,8 +225,10 @@ google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.5.0 h1:Ljk6PdHdOhAb5aDMWXjDLMMhph+BpztA4v1QdqEW2eY= +gotest.tools/v3 v3.5.0/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU= diff --git a/pkg/etc/checker.go b/pkg/etc/checker.go index b69a0a80..9f777e25 100644 --- a/pkg/etc/checker.go +++ b/pkg/etc/checker.go @@ -3,82 +3,72 @@ package etc import ( "errors" "fmt" + "log/slog" "os" - - log "github.com/sirupsen/logrus" ) // Check checks config values to fail fast in case of any problems // that we might have due to invalid config. -func Check(config Config) (err error) { - log.WithFields(log.Fields{ - "pid": os.Getpid(), - }).Debug("Current process") +func Check(config Config) error { + slog.Debug("Current process", slog.Int("pid", os.Getpid())) - log.WithFields(log.Fields{ - "uid": os.Getuid(), - "gid": os.Getegid(), - "home_dir": os.Getenv("HOME"), - }).Debug("Current user") + slog.Debug("Current user", + slog.Int("uid", os.Getuid()), + slog.Int("gid", os.Getegid()), + slog.String("home_dir", os.Getenv("HOME")), + ) if config.Trivy.CacheDir == "" { - err = errors.New("trivy cache dir must not be blank") - return + return errors.New("trivy cache dir must not be blank") } if config.Trivy.ReportsDir == "" { - err = errors.New("trivy reports dir must not be blank") - return + return errors.New("trivy reports dir must not be blank") } - if err = ensureDirExists(config.Trivy.CacheDir, "trivy cache dir"); err != nil { - return + if err := ensureDirExists(config.Trivy.CacheDir, "trivy cache dir"); err != nil { + return err } - if err = ensureDirExists(config.Trivy.ReportsDir, "trivy reports dir"); err != nil { - return + if err := ensureDirExists(config.Trivy.ReportsDir, "trivy reports dir"); err != nil { + return err } if config.API.IsTLSEnabled() { if !fileExists(config.API.TLSCertificate) { - err = fmt.Errorf("TLS certificate file does not exist: %s", config.API.TLSCertificate) - return + return fmt.Errorf("TLS certificate file does not exist: %s", config.API.TLSCertificate) } if !fileExists(config.API.TLSKey) { - err = fmt.Errorf("TLS private key file does not exist: %s", config.API.TLSKey) - return + return fmt.Errorf("TLS private key file does not exist: %s", config.API.TLSKey) } for _, path := range config.API.ClientCAs { if !fileExists(path) { - err = fmt.Errorf("ClientCA file does not exist: %s", path) - return + return fmt.Errorf("ClientCA file does not exist: %s", path) } } } - return + return nil } -func ensureDirExists(path, description string) (err error) { +func ensureDirExists(path, description string) error { + logger := slog.With(slog.String("path", path)) if !dirExists(path) { - log.WithField("path", path).Warnf("%s does not exist", description) - log.WithField("path", path).Debugf("Creating %s", description) - if err = os.MkdirAll(path, 0777); err != nil { - err = fmt.Errorf("creating %s: %w", description, err) - return + logger.Warn(fmt.Sprintf("%s does not exist", description)) + logger.Debug(fmt.Sprintf("Creating %s", description)) + if err := os.MkdirAll(path, 0777); err != nil { + return fmt.Errorf("creating %s: %w", description, err) } } fi, err := os.Stat(path) if err != nil { - return + return err } - log.WithFields(log.Fields{ - "mode": fi.Mode().String(), - }).Debugf("%s permissions", description) - return + logger.Debug(fmt.Sprintf("%s permissions", description), slog.String("mode", fi.Mode().String())) + return nil } // dirExists checks if a dir exists before we diff --git a/pkg/etc/config.go b/pkg/etc/config.go index 7e1e8219..0b60ccc5 100644 --- a/pkg/etc/config.go +++ b/pkg/etc/config.go @@ -1,12 +1,13 @@ package etc import ( + "log/slog" "os" + "strings" "time" "github.com/aquasecurity/harbor-scanner-trivy/pkg/harbor" "github.com/caarlos0/env/v6" - "github.com/sirupsen/logrus" ) type BuildInfo struct { @@ -73,15 +74,21 @@ type RedisPool struct { WriteTimeout time.Duration `env:"SCANNER_REDIS_POOL_WRITE_TIMEOUT" envDefault:"1s"` } -func GetLogLevel() logrus.Level { +func LogLevel() slog.Level { if value, ok := os.LookupEnv("SCANNER_LOG_LEVEL"); ok { - level, err := logrus.ParseLevel(value) - if err != nil { - return logrus.InfoLevel + switch strings.ToLower(value) { + case "error": + return slog.LevelError + case "warn", "warning": + return slog.LevelWarn + case "info": + return slog.LevelInfo + case "trace", "debug": + return slog.LevelDebug } - return level + return slog.LevelInfo } - return logrus.InfoLevel + return slog.LevelInfo } func GetConfig() (Config, error) { @@ -92,7 +99,7 @@ func GetConfig() (Config, error) { } if _, ok := os.LookupEnv("SCANNER_TRIVY_DEBUG_MODE"); !ok { - if GetLogLevel() == logrus.DebugLevel { + if LogLevel() == slog.LevelDebug { cfg.Trivy.DebugMode = true } } diff --git a/pkg/etc/config_test.go b/pkg/etc/config_test.go index e3758756..bd3132df 100644 --- a/pkg/etc/config_test.go +++ b/pkg/etc/config_test.go @@ -1,12 +1,11 @@ package etc import ( - "os" + "log/slog" "testing" "time" "github.com/aquasecurity/harbor-scanner-trivy/pkg/harbor" - "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -17,32 +16,32 @@ func TestGetLogLevel(t *testing.T) { testCases := []struct { Name string Envs Envs - ExpectedLogLevel logrus.Level + ExpectedLogLevel slog.Level }{ { Name: "Should return default log level when env is not set", - ExpectedLogLevel: logrus.InfoLevel, + ExpectedLogLevel: slog.LevelInfo, }, { Name: "Should return default log level when env has invalid value", Envs: Envs{ "SCANNER_LOG_LEVEL": "unknown_level", }, - ExpectedLogLevel: logrus.InfoLevel, + ExpectedLogLevel: slog.LevelInfo, }, { Name: "Should return log level set as env", Envs: Envs{ - "SCANNER_LOG_LEVEL": "trace", + "SCANNER_LOG_LEVEL": "debug", }, - ExpectedLogLevel: logrus.TraceLevel, + ExpectedLogLevel: slog.LevelDebug, }, } for _, tc := range testCases { t.Run(tc.Name, func(t *testing.T) { - setenvs(t, tc.Envs) - assert.Equal(t, tc.ExpectedLogLevel, GetLogLevel()) + setEnvs(t, tc.Envs) + assert.Equal(t, tc.ExpectedLogLevel, LogLevel()) }) } } @@ -219,7 +218,7 @@ func TestGetConfig(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - setenvs(t, tc.envs) + setEnvs(t, tc.envs) config, err := GetConfig() assert.Equal(t, tc.expectedError, err) assert.Equal(t, tc.expectedConfig, config) @@ -245,18 +244,15 @@ func TestGetScannerMetadata(t *testing.T) { } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - setenvs(t, tc.envs) + setEnvs(t, tc.envs) assert.Equal(t, tc.expectedScanner, GetScannerMetadata()) }) } } -func setenvs(t *testing.T, envs Envs) { - t.Helper() - os.Clearenv() +func setEnvs(t *testing.T, envs Envs) { for k, v := range envs { - err := os.Setenv(k, v) - require.NoError(t, err) + t.Setenv(k, v) } } diff --git a/pkg/http/api/base_handler.go b/pkg/http/api/base_handler.go index 7c516170..30fb5b75 100644 --- a/pkg/http/api/base_handler.go +++ b/pkg/http/api/base_handler.go @@ -3,11 +3,11 @@ package api import ( "encoding/json" "fmt" + "log/slog" "net/http" "strings" "github.com/aquasecurity/harbor-scanner-trivy/pkg/harbor" - log "github.com/sirupsen/logrus" ) const ( @@ -71,7 +71,7 @@ func (h *BaseHandler) WriteJSON(res http.ResponseWriter, data interface{}, mimeT err := json.NewEncoder(res).Encode(data) if err != nil { - log.WithError(err).Error("Error while writing JSON") + slog.Error("Error while writing JSON", slog.String("err", err.Error())) h.SendInternalServerError(res) return } diff --git a/pkg/http/api/server.go b/pkg/http/api/server.go index bdb2b14d..bd859614 100644 --- a/pkg/http/api/server.go +++ b/pkg/http/api/server.go @@ -3,13 +3,14 @@ package api import ( "crypto/tls" "crypto/x509" + "errors" "fmt" + "log/slog" "net/http" "os" "strings" "github.com/aquasecurity/harbor-scanner-trivy/pkg/etc" - log "github.com/sirupsen/logrus" "golang.org/x/net/context" ) @@ -73,31 +74,32 @@ func NewServer(config etc.API, handler http.Handler) (server *Server, err error) func (s *Server) ListenAndServe() { go func() { - if err := s.listenAndServe(); err != http.ErrServerClosed { - log.Fatalf("Error: %v", err) + if err := s.listenAndServe(); errors.Is(err, http.ErrServerClosed) { + slog.Error("Error", slog.String("err", err.Error())) + os.Exit(1) } - log.Trace("API server stopped listening for incoming connections") + slog.Debug("API server stopped listening for incoming connections") }() } func (s *Server) listenAndServe() error { if s.config.IsTLSEnabled() { - log.WithFields(log.Fields{ - "certificate": s.config.TLSCertificate, - "key": s.config.TLSKey, - "clientCAs": strings.Join(s.config.ClientCAs, ", "), - "addr": s.config.Addr, - }).Debug("Starting API server with TLS") + slog.Debug("Starting API server with TLS", + slog.String("certificate", s.config.TLSCertificate), + slog.String("key", s.config.TLSKey), + slog.String("clientCAs", strings.Join(s.config.ClientCAs, ", ")), + slog.String("addr", s.config.Addr), + ) return s.server.ListenAndServeTLS(s.config.TLSCertificate, s.config.TLSKey) } - log.WithField("addr", s.config.Addr).Warn("Starting API server without TLS") + slog.Warn("Starting API server without TLS", slog.String("addr", s.config.Addr)) return s.server.ListenAndServe() } func (s *Server) Shutdown() { - log.Trace("API server shutdown started") + slog.Debug("API server shutdown started") if err := s.server.Shutdown(context.Background()); err != nil { - log.WithError(err).Error("Error while shutting down API server") + slog.Error("Error while shutting down API server", slog.String("err", err.Error())) } - log.Trace("API server shutdown completed") + slog.Debug("API server shutdown completed") } diff --git a/pkg/http/api/v1/handler.go b/pkg/http/api/v1/handler.go index 7f38ccc1..a7fc9794 100644 --- a/pkg/http/api/v1/handler.go +++ b/pkg/http/api/v1/handler.go @@ -3,6 +3,7 @@ package v1 import ( "encoding/json" "fmt" + "log/slog" "net/http" "net/url" "strconv" @@ -17,14 +18,11 @@ import ( "github.com/aquasecurity/harbor-scanner-trivy/pkg/trivy" "github.com/gorilla/mux" "github.com/prometheus/client_golang/prometheus/promhttp" - log "github.com/sirupsen/logrus" ) const ( pathVarScanRequestID = "scan_request_id" -) -const ( propertyScannerType = "harbor.scanner-adapter/scanner-type" propertyDBUpdatedAt = "harbor.scanner-adapter/vulnerability-database-updated-at" propertyDBNextUpdateAt = "harbor.scanner-adapter/vulnerability-database-next-update-at" @@ -67,16 +65,20 @@ func NewAPIHandler(info etc.BuildInfo, config etc.Config, enqueuer queue.Enqueue func (h *requestHandler) logRequest(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - log.Tracef("%s - %s %s %s", r.RemoteAddr, r.Proto, r.Method, r.URL.RequestURI()) + slog.Debug("Request", + slog.String("addr", r.RemoteAddr), + slog.String("proto", r.Proto), + slog.String("method", r.Method), + slog.String("uri", r.URL.RequestURI()), + ) next.ServeHTTP(w, r) }) } func (h *requestHandler) AcceptScanRequest(res http.ResponseWriter, req *http.Request) { scanRequest := harbor.ScanRequest{} - err := json.NewDecoder(req.Body).Decode(&scanRequest) - if err != nil { - log.WithError(err).Error("Error while unmarshalling scan request") + if err := json.NewDecoder(req.Body).Decode(&scanRequest); err != nil { + slog.Error("Error while unmarshalling scan request", slog.String("err", err.Error())) h.WriteJSONError(res, harbor.Error{ HTTPCode: http.StatusBadRequest, Message: fmt.Sprintf("unmarshalling scan request: %s", err.Error()), @@ -85,14 +87,14 @@ func (h *requestHandler) AcceptScanRequest(res http.ResponseWriter, req *http.Re } if validationError := h.ValidateScanRequest(scanRequest); validationError != nil { - log.Errorf("Error while validating scan request: %s", validationError.Message) + slog.Error("Error while validating scan request", slog.String("err", validationError.Message)) h.WriteJSONError(res, *validationError) return } scanJob, err := h.enqueuer.Enqueue(scanRequest) if err != nil { - log.WithError(err).Error("Error while enqueuing scan job") + slog.Error("Error while enqueuing scan job", slog.String("err", err.Error())) h.WriteJSONError(res, harbor.Error{ HTTPCode: http.StatusInternalServerError, Message: fmt.Sprintf("enqueuing scan job: %s", err.Error()), @@ -113,8 +115,7 @@ func (h *requestHandler) ValidateScanRequest(req harbor.ScanRequest) *harbor.Err } } - _, err := url.ParseRequestURI(req.Registry.URL) - if err != nil { + if _, err := url.ParseRequestURI(req.Registry.URL); err != nil { return &harbor.Error{ HTTPCode: http.StatusUnprocessableEntity, Message: "invalid registry.url", @@ -141,8 +142,7 @@ func (h *requestHandler) ValidateScanRequest(req harbor.ScanRequest) *harbor.Err func (h *requestHandler) GetScanReport(res http.ResponseWriter, req *http.Request) { var reportMimeType api.MimeType - err := reportMimeType.FromAcceptHeader(req.Header.Get(api.HeaderAccept)) - if err != nil { + if err := reportMimeType.FromAcceptHeader(req.Header.Get(api.HeaderAccept)); err != nil { h.WriteJSONError(res, harbor.Error{ HTTPCode: http.StatusUnsupportedMediaType, Message: fmt.Sprintf("unsupported media type %s", req.Header.Get(api.HeaderAccept)), @@ -153,7 +153,7 @@ func (h *requestHandler) GetScanReport(res http.ResponseWriter, req *http.Reques vars := mux.Vars(req) scanJobID, ok := vars[pathVarScanRequestID] if !ok { - log.Error("Error while parsing `scan_request_id` path variable") + slog.Error("Error while parsing `scan_request_id` path variable") h.WriteJSONError(res, harbor.Error{ HTTPCode: http.StatusBadRequest, Message: "missing scan_request_id", @@ -161,7 +161,7 @@ func (h *requestHandler) GetScanReport(res http.ResponseWriter, req *http.Reques return } - reqLog := log.WithField("scan_job_id", scanJobID) + reqLog := slog.With(slog.String("scan_job_id", scanJobID)) scanJob, err := h.store.Get(scanJobID) if err != nil { @@ -182,15 +182,17 @@ func (h *requestHandler) GetScanReport(res http.ResponseWriter, req *http.Reques return } + scanJobLog := reqLog.With(slog.String("scan_job_status", scanJob.Status.String())) + if scanJob.Status == job.Queued || scanJob.Status == job.Pending { - reqLog.WithField("scan_job_status", scanJob.Status).Debug("Scan job has not finished yet") + scanJobLog.Debug("Scan job has not finished yet") res.Header().Add("Location", req.URL.String()) res.WriteHeader(http.StatusFound) return } if scanJob.Status == job.Failed { - reqLog.WithField(log.ErrorKey, scanJob.Error).Error("Scan job failed") + scanJobLog.Error("Scan job failed", slog.String("err", scanJob.Error)) h.WriteJSONError(res, harbor.Error{ HTTPCode: http.StatusInternalServerError, Message: scanJob.Error, @@ -199,7 +201,7 @@ func (h *requestHandler) GetScanReport(res http.ResponseWriter, req *http.Reques } if scanJob.Status != job.Finished { - reqLog.WithField("scan_job_status", scanJob.Status).Error("Unexpected scan job status") + scanJobLog.Error("Unexpected scan job status") h.WriteJSONError(res, harbor.Error{ HTTPCode: http.StatusInternalServerError, Message: fmt.Sprintf("unexpected status %v of scan job %v", scanJob.Status, scanJob.ID), @@ -232,7 +234,7 @@ func (h *requestHandler) GetMetadata(res http.ResponseWriter, _ *http.Request) { vi, err := h.wrapper.GetVersion() if err != nil { - log.WithError(err).Error("Error while retrieving vulnerability DB version") + slog.Error("Error while retrieving vulnerability DB version", slog.String("err", err.Error())) } if err == nil && vi.VulnerabilityDB != nil { diff --git a/pkg/persistence/redis/store.go b/pkg/persistence/redis/store.go index 0934f439..07535788 100644 --- a/pkg/persistence/redis/store.go +++ b/pkg/persistence/redis/store.go @@ -2,14 +2,15 @@ package redis import ( "encoding/json" + "errors" "fmt" + "log/slog" "github.com/aquasecurity/harbor-scanner-trivy/pkg/etc" "github.com/aquasecurity/harbor-scanner-trivy/pkg/harbor" "github.com/aquasecurity/harbor-scanner-trivy/pkg/job" "github.com/aquasecurity/harbor-scanner-trivy/pkg/persistence" "github.com/gomodule/redigo/redis" - log "github.com/sirupsen/logrus" "golang.org/x/xerrors" ) @@ -36,15 +37,14 @@ func (s *store) Create(scanJob job.ScanJob) error { key := s.getKeyForScanJob(scanJob.ID) - log.WithFields(log.Fields{ - "scan_job_id": scanJob.ID, - "scan_job_status": scanJob.Status.String(), - "redis_key": key, - "expire": s.cfg.ScanJobTTL.Seconds(), - }).Debug("Saving scan job") + slog.Debug("Saving scan job", + slog.String("scan_job_id", scanJob.ID), + slog.String("scan_job_status", scanJob.Status.String()), + slog.String("redis_key", key), + slog.Duration("expire", s.cfg.ScanJobTTL), + ) - _, err = conn.Do("SET", key, string(bytes), "NX", "EX", int(s.cfg.ScanJobTTL.Seconds())) - if err != nil { + if _, err = conn.Do("SET", key, string(bytes), "NX", "EX", int(s.cfg.ScanJobTTL.Seconds())); err != nil { return xerrors.Errorf("creating scan job: %w", err) } @@ -62,15 +62,14 @@ func (s *store) update(scanJob job.ScanJob) error { key := s.getKeyForScanJob(scanJob.ID) - log.WithFields(log.Fields{ - "scan_job_id": scanJob.ID, - "scan_job_status": scanJob.Status.String(), - "redis_key": key, - "expire": s.cfg.ScanJobTTL.Seconds(), - }).Debug("Updating scan job") + slog.Debug("Updating scan job", + slog.String("scan_job_id", scanJob.ID), + slog.String("scan_job_status", scanJob.Status.String()), + slog.String("redis_key", key), + slog.Duration("expire", s.cfg.ScanJobTTL), + ) - _, err = conn.Do("SET", key, string(bytes), "XX", "EX", int(s.cfg.ScanJobTTL.Seconds())) - if err != nil { + if _, err = conn.Do("SET", key, string(bytes), "XX", "EX", int(s.cfg.ScanJobTTL.Seconds())); err != nil { return xerrors.Errorf("updating scan job: %w", err) } @@ -84,7 +83,7 @@ func (s *store) Get(scanJobID string) (*job.ScanJob, error) { key := s.getKeyForScanJob(scanJobID) value, err := redis.String(conn.Do("GET", key)) if err != nil { - if err == redis.ErrNil { + if errors.Is(err, redis.ErrNil) { return nil, nil } return nil, err @@ -100,10 +99,9 @@ func (s *store) Get(scanJobID string) (*job.ScanJob, error) { } func (s *store) UpdateStatus(scanJobID string, newStatus job.ScanJobStatus, error ...string) error { - log.WithFields(log.Fields{ - "scan_job_id": scanJobID, - "new_status": newStatus.String(), - }).Debug("Updating status for scan job") + slog.Debug("Updating status for scan job", slog.String("scan_job_id", scanJobID), + slog.String("new_status", newStatus.String()), + ) scanJob, err := s.Get(scanJobID) if err != nil { @@ -119,9 +117,7 @@ func (s *store) UpdateStatus(scanJobID string, newStatus job.ScanJobStatus, erro } func (s *store) UpdateReport(scanJobID string, report harbor.ScanReport) error { - log.WithFields(log.Fields{ - "scan_job_id": scanJobID, - }).Debug("Updating reports for scan job") + slog.Debug("Updating reports for scan job", slog.String("scan_job_id", scanJobID)) scanJob, err := s.Get(scanJobID) if err != nil { @@ -139,6 +135,6 @@ func (s *store) getKeyForScanJob(scanJobID string) string { func (s *store) close(conn redis.Conn) { err := conn.Close() if err != nil { - log.WithError(err).Error("Error while closing connection") + slog.Error("Error while closing connection", slog.String("err", err.Error())) } } diff --git a/pkg/queue/enqueuer.go b/pkg/queue/enqueuer.go index bc6e8a11..4ff8ab30 100644 --- a/pkg/queue/enqueuer.go +++ b/pkg/queue/enqueuer.go @@ -3,14 +3,15 @@ package queue import ( "encoding/json" "fmt" + "log/slog" + + "github.com/gocraft/work" + "github.com/gomodule/redigo/redis" "github.com/aquasecurity/harbor-scanner-trivy/pkg/etc" "github.com/aquasecurity/harbor-scanner-trivy/pkg/harbor" "github.com/aquasecurity/harbor-scanner-trivy/pkg/job" "github.com/aquasecurity/harbor-scanner-trivy/pkg/persistence" - "github.com/gocraft/work" - "github.com/gomodule/redigo/redis" - log "github.com/sirupsen/logrus" ) const ( @@ -35,7 +36,7 @@ func NewEnqueuer(config etc.JobQueue, redisPool *redis.Pool, store persistence.S } func (e *enqueuer) Enqueue(request harbor.ScanRequest) (job.ScanJob, error) { - log.Debug("Enqueueing scan job") + slog.Debug("Enqueueing scan job") b, err := json.Marshal(request) if err != nil { @@ -48,15 +49,14 @@ func (e *enqueuer) Enqueue(request harbor.ScanRequest) (job.ScanJob, error) { if err != nil { return job.ScanJob{}, fmt.Errorf("enqueuing scan artifact job: %v", err) } - log.Debug("Successfully enqueued scan job") + slog.Debug("Successfully enqueued scan job", slog.String("job_id", j.ID)) scanJob := job.ScanJob{ ID: j.ID, Status: job.Queued, } - err = e.store.Create(scanJob) - if err != nil { + if err = e.store.Create(scanJob); err != nil { return job.ScanJob{}, fmt.Errorf("creating scan job %v", err) } diff --git a/pkg/queue/worker.go b/pkg/queue/worker.go index edbb6106..eefea8ac 100644 --- a/pkg/queue/worker.go +++ b/pkg/queue/worker.go @@ -3,14 +3,14 @@ package queue import ( "encoding/json" "fmt" + "log/slog" + "github.com/gocraft/work" "github.com/gomodule/redigo/redis" "github.com/aquasecurity/harbor-scanner-trivy/pkg/etc" "github.com/aquasecurity/harbor-scanner-trivy/pkg/harbor" "github.com/aquasecurity/harbor-scanner-trivy/pkg/scan" - "github.com/gocraft/work" - log "github.com/sirupsen/logrus" ) const ( @@ -55,9 +55,9 @@ func (w *worker) Start() { } func (w *worker) Stop() { - log.Trace("Job queue shutdown started") + slog.Debug("Job queue shutdown started") w.workerPool.Stop() - log.Trace("Job queue shutdown completed") + slog.Debug("Job queue shutdown completed") } // workerContext is a context for running scan jobs. @@ -66,22 +66,20 @@ type workerContext struct { } // ScanArtifact is a handler function for the specified scan Job with the given workerContext. -func (s *workerContext) ScanArtifact(job *work.Job) (err error) { - log.WithField("scan_job_id", job.ID).Debug("Executing enqueued scan job") +func (s *workerContext) ScanArtifact(job *work.Job) error { + slog.Debug("Executing enqueued scan job", slog.String("scan_job_id", job.ID)) request, err := s.unmarshalScanRequest(job) if err != nil { - return + return err } - err = s.controller.Scan(job.ID, request) - return + return s.controller.Scan(job.ID, request) } func (s *workerContext) unmarshalScanRequest(job *work.Job) (request harbor.ScanRequest, err error) { // TODO Fail fast and assert that the scan_request arg was set by the enqueuer. - err = json.Unmarshal([]byte(job.ArgString(scanRequestJobArg)), &request) - if err != nil { + if err = json.Unmarshal([]byte(job.ArgString(scanRequestJobArg)), &request); err != nil { return request, fmt.Errorf("unmarshalling scan request: %v", err) } return diff --git a/pkg/redisx/pool.go b/pkg/redisx/pool.go index b881a121..c7dcb196 100644 --- a/pkg/redisx/pool.go +++ b/pkg/redisx/pool.go @@ -3,17 +3,16 @@ package redisx import ( "errors" "fmt" + "log/slog" "net/url" "strconv" "strings" "time" "github.com/FZambia/sentinel" + "github.com/gomodule/redigo/redis" "github.com/aquasecurity/harbor-scanner-trivy/pkg/etc" - - "github.com/gomodule/redigo/redis" - log "github.com/sirupsen/logrus" ) // NewPool constructs a redis.Pool with the specified configuration. @@ -42,7 +41,7 @@ func NewPool(config etc.RedisPool) (pool *redis.Pool, err error) { func newInstancePool(config etc.RedisPool) *redis.Pool { return &redis.Pool{ Dial: func() (redis.Conn, error) { - log.WithField("url", config.URL).Trace("Connecting to Redis") + slog.Debug("Connecting to Redis", slog.String("url", config.URL)) return redis.DialURL(config.URL) }, MaxIdle: config.MaxIdle, @@ -54,7 +53,7 @@ func newInstancePool(config etc.RedisPool) *redis.Pool { // redis+sentinel://user:password@sentinel_host1:port1,sentinel_host2:port2/monitor-name/db-number func newSentinelPool(configURL *url.URL, config etc.RedisPool) (pool *redis.Pool, err error) { - log.Trace("Constructing connection pool for Redis Sentinel") + slog.Debug("Constructing connection pool for Redis Sentinel") sentinelURL, err := ParseSentinelURL(configURL) if err != nil { return @@ -77,7 +76,7 @@ func newSentinelPool(configURL *url.URL, config etc.RedisPool) (pool *redis.Pool Addrs: sentinelURL.Addrs, MasterName: sentinelURL.MonitorName, Dial: func(addr string) (conn redis.Conn, err error) { - log.WithField("addr", addr).Trace("Connecting to Redis sentinel") + slog.Debug("Connecting to Redis sentinel", slog.String("addr", addr)) conn, err = redis.Dial("tcp", addr, sentinelOpts...) if err != nil { return @@ -97,14 +96,14 @@ func newSentinelPool(configURL *url.URL, config etc.RedisPool) (pool *redis.Pool if err != nil { return } - log.WithField("addr", masterAddr).Trace("Connecting to Redis master") + slog.Debug("Connecting to Redis master", slog.String("addr", masterAddr)) return redis.Dial("tcp", masterAddr, redisOpts...) }, TestOnBorrow: func(c redis.Conn, t time.Time) error { if time.Since(t) < time.Minute { return nil } - log.Trace("Testing connection to Redis master on borrow") + slog.Debug("Testing connection to Redis master on borrow") if !sentinel.TestRole(c, "master") { return errors.New("role check failed") } diff --git a/pkg/scan/controller.go b/pkg/scan/controller.go index bc9990a9..3772c4cd 100644 --- a/pkg/scan/controller.go +++ b/pkg/scan/controller.go @@ -2,13 +2,13 @@ package scan import ( "encoding/base64" + "log/slog" "strings" "github.com/aquasecurity/harbor-scanner-trivy/pkg/harbor" "github.com/aquasecurity/harbor-scanner-trivy/pkg/job" "github.com/aquasecurity/harbor-scanner-trivy/pkg/persistence" "github.com/aquasecurity/harbor-scanner-trivy/pkg/trivy" - log "github.com/sirupsen/logrus" "golang.org/x/xerrors" ) @@ -31,11 +31,9 @@ func NewController(store persistence.Store, wrapper trivy.Wrapper, transformer T } func (c *controller) Scan(scanJobID string, request harbor.ScanRequest) error { - err := c.scan(scanJobID, request) - if err != nil { - log.WithError(err).Error("Scan failed") - err = c.store.UpdateStatus(scanJobID, job.Failed, err.Error()) - if err != nil { + if err := c.scan(scanJobID, request); err != nil { + slog.Error("Scan failed", slog.String("err", err.Error())) + if err = c.store.UpdateStatus(scanJobID, job.Failed, err.Error()); err != nil { return xerrors.Errorf("updating scan job as failed: %v", err) } } diff --git a/pkg/scan/transformer.go b/pkg/scan/transformer.go index 5902b633..d61610aa 100644 --- a/pkg/scan/transformer.go +++ b/pkg/scan/transformer.go @@ -1,12 +1,12 @@ package scan import ( + "log/slog" "time" "github.com/aquasecurity/harbor-scanner-trivy/pkg/etc" "github.com/aquasecurity/harbor-scanner-trivy/pkg/harbor" "github.com/aquasecurity/harbor-scanner-trivy/pkg/trivy" - log "github.com/sirupsen/logrus" ) // Clock wraps the Now method. Introduced to allow replacing the global state with fixed clocks to facilitate testing. @@ -96,12 +96,13 @@ func (t *transformer) toHarborLayer(tLayer *trivy.Layer) (hLayer *harbor.Layer) } func (t *transformer) toHarborSeverity(severity string) harbor.Severity { - if harborSev, ok := trivyToHarborSeverityMap[severity]; ok { - return harborSev + harborSev, ok := trivyToHarborSeverityMap[severity] + if !ok { + slog.Warn("Unknown trivy severity", slog.String("severity", severity)) + return harbor.SevUnknown } - log.WithField("severity", severity).Warn("Unknown trivy severity") - return harbor.SevUnknown + return harborSev } func (t *transformer) toVendorAttributes(info map[string]trivy.CVSSInfo) map[string]interface{} { diff --git a/pkg/trivy/wrapper.go b/pkg/trivy/wrapper.go index 855d7f0b..083eaabb 100644 --- a/pkg/trivy/wrapper.go +++ b/pkg/trivy/wrapper.go @@ -4,12 +4,12 @@ import ( "encoding/json" "fmt" "io" + "log/slog" "os/exec" "strings" "github.com/aquasecurity/harbor-scanner-trivy/pkg/etc" "github.com/aquasecurity/harbor-scanner-trivy/pkg/ext" - log "github.com/sirupsen/logrus" ) const ( @@ -56,18 +56,18 @@ func NewWrapper(config etc.Trivy, ambassador ext.Ambassador) Wrapper { } func (w *wrapper) Scan(imageRef ImageRef) ([]Vulnerability, error) { - log.WithField("image_ref", imageRef.Name).Debug("Started scanning") + logger := slog.With(slog.String("image_ref", imageRef.Name)) + logger.Debug("Started scanning") reportFile, err := w.ambassador.TempFile(w.config.ReportsDir, "scan_report_*.json") if err != nil { return nil, err } - log.WithField("path", reportFile.Name()).Debug("Saving scan report to tmp file") + logger.Debug("Saving scan report to tmp file", slog.String("path", reportFile.Name())) defer func() { - log.WithField("path", reportFile.Name()).Debug("Removing scan report tmp file") - err := w.ambassador.Remove(reportFile.Name()) - if err != nil { - log.WithError(err).Warn("Error while removing scan report tmp file") + logger.Debug("Removing scan report tmp file", slog.String("path", reportFile.Name())) + if err = w.ambassador.Remove(reportFile.Name()); err != nil { + logger.Warn("Error while removing scan report tmp file", slog.String("err", err.Error())) } }() @@ -76,31 +76,29 @@ func (w *wrapper) Scan(imageRef ImageRef) ([]Vulnerability, error) { return nil, err } - log.WithFields(log.Fields{"path": cmd.Path, "args": cmd.Args}).Trace("Exec command with args") + logger.Debug("Exec command with args", slog.String("path", cmd.Path), + slog.String("args", strings.Join(cmd.Args, " "))) stdout, err := w.ambassador.RunCmd(cmd) if err != nil { - log.WithFields(log.Fields{ - "image_ref": imageRef.Name, - "exit_code": cmd.ProcessState.ExitCode(), - "std_out": string(stdout), - }).Error("Running trivy failed") + logger.Error("Running trivy failed", + slog.String("exit_code", fmt.Sprintf("%d", cmd.ProcessState.ExitCode())), + slog.String("std_out", string(stdout)), + ) return nil, fmt.Errorf("running trivy: %v: %v", err, string(stdout)) } - log.WithFields(log.Fields{ - "image_ref": imageRef.Name, - "exit_code": cmd.ProcessState.ExitCode(), - "std_out": string(stdout), - }).Debug("Running trivy finished") + logger.Debug("Running trivy finished", + slog.String("exit_code", fmt.Sprintf("%d", cmd.ProcessState.ExitCode())), + slog.String("std_out", string(stdout)), + ) return w.parseVulnerabilities(reportFile) } func (w *wrapper) parseVulnerabilities(reportFile io.Reader) ([]Vulnerability, error) { var scanReport ScanReport - err := json.NewDecoder(reportFile).Decode(&scanReport) - if err != nil { + if err := json.NewDecoder(reportFile).Decode(&scanReport); err != nil { return nil, fmt.Errorf("decoding scan report from file: %w", err) } @@ -110,7 +108,7 @@ func (w *wrapper) parseVulnerabilities(reportFile io.Reader) ([]Vulnerability, e var vulnerabilities []Vulnerability for _, scanResult := range scanReport.Results { - log.WithField("target", scanResult.Target).Trace("Parsing vulnerabilities") + slog.Debug("Parsing vulnerabilities", slog.String("target", scanResult.Target)) vulnerabilities = append(vulnerabilities, scanResult.Vulnerabilities...) } From 2cad13ad1257ab88820dd4eb52414c6cefdb1987 Mon Sep 17 00:00:00 2001 From: knqyf263 Date: Thu, 26 Oct 2023 11:33:03 +0900 Subject: [PATCH 2/2] ci: use go-version-file Signed-off-by: knqyf263 --- .github/workflows/build.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9d9e6bff..a851de37 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -29,12 +29,12 @@ jobs: name: Build runs-on: ubuntu-20.04 steps: + - name: Checkout code + uses: actions/checkout@v4 - name: Setup Go uses: actions/setup-go@v4 with: - go-version: 1.20.5 - - name: Checkout code - uses: actions/checkout@v4 + go-version-file: go.mod - name: yaml-lint uses: ibiqlik/action-yamllint@v3 - name: Setup make