diff --git a/.golangci.yml b/.golangci.yml index 9cd559d7..a52f62a7 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -68,7 +68,6 @@ linters: - all - '-ST1003' # waiting for package name will be fixed (underscores) - '-QF1008' # not need to fix; we understand how to call nested structs - - '-SA1019' # remove when fix logger revive: rules: - name: var-naming # waiting for package name will be fixed (incorrect naming) diff --git a/cmd/dmt/main.go b/cmd/dmt/main.go index e7d7e42e..46233668 100644 --- a/cmd/dmt/main.go +++ b/cmd/dmt/main.go @@ -19,15 +19,17 @@ package main import ( "context" "errors" + "log/slog" "os" "runtime" "runtime/pprof" "github.com/fatih/color" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/flags" "github.com/deckhouse/dmt/internal/fsutils" - "github.com/deckhouse/dmt/internal/logger" "github.com/deckhouse/dmt/internal/manager" "github.com/deckhouse/dmt/internal/metrics" "github.com/deckhouse/dmt/internal/version" @@ -40,17 +42,17 @@ func main() { func runLint(dir string) error { if flags.PprofFile != "" { - logger.InfoF("Profiling enabled. Profile file: %s", flags.PprofFile) + log.Info("Profiling enabled", slog.String("file", flags.PprofFile)) defer func() { pproFile, err := fsutils.ExpandDir(flags.PprofFile) if err != nil { - logger.ErrorF("could not get current working directory: %s", err) + log.Error("could not get current working directory", log.Err(err)) return } - logger.InfoF("Writing memory profile to %s", pproFile) + log.Info("Writing memory profile", slog.String("file", pproFile)) f, err := os.Create(pproFile) if err != nil { - logger.ErrorF("could not create memory profile: %s", err) + log.Error("could not create memory profile", log.Err(err)) return } defer f.Close() @@ -59,17 +61,19 @@ func runLint(dir string) error { // Alternatively, use Lookup("heap") for a profile // that has inuse_space as the default index. if err := pprof.Lookup("allocs").WriteTo(f, 0); err != nil { - logger.ErrorF("could not write memory profile: %s", err) + log.Error("could not write memory profile", log.Err(err)) return } }() } // enable color output for Github actions, do not remove it color.NoColor = false - logger.InfoF("DMT version: %s, Commit: %s, Date: %s", version.Version, version.Commit, version.Date) + log.Info("DMT version", slog.String("version", version.Version), slog.String("commit", version.Commit), slog.String("date", version.Date)) cfg, err := config.NewDefaultRootConfig(dir) - logger.CheckErr(err) + if err != nil { + log.Fatal("default root config", log.Err(err)) //nolint:gocritic + } // init metrics storage, should be done before running manager metrics.GetClient(dir) diff --git a/cmd/dmt/root.go b/cmd/dmt/root.go index 664c03da..9e2e8c1b 100644 --- a/cmd/dmt/root.go +++ b/cmd/dmt/root.go @@ -20,6 +20,7 @@ import ( "bytes" "errors" "fmt" + "log/slog" "os" "regexp" "strings" @@ -28,10 +29,11 @@ import ( "github.com/fatih/color" "github.com/spf13/cobra" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/bootstrap" "github.com/deckhouse/dmt/internal/flags" "github.com/deckhouse/dmt/internal/fsutils" - "github.com/deckhouse/dmt/internal/logger" "github.com/deckhouse/dmt/internal/version" ) @@ -49,7 +51,12 @@ func execute() { PersistentPreRun: func(_ *cobra.Command, _ []string) { // TODO: move to separate package flags.Version = version.Version - logger.InitLogger(os.Stdout, flags.LogLevel) + lvl := log.LogLevelFromStr(flags.LogLevel) + logger := log.NewLogger( + log.WithLevel(slog.Level(lvl)), + log.WithHandlerType(log.TextHandlerType), + ) + log.SetDefault(logger) }, } @@ -170,15 +177,15 @@ func runLintMultiple(dirs []string) error { for _, dir := range dirs { expandedDir, err := fsutils.ExpandDir(dir) if err != nil { - logger.ErrorF("Error expanding directory %s: %v", dir, err) + log.Error("Error expanding directory", slog.String("dir", dir), log.Err(err)) continue } - logger.InfoF("Processing directory: %s", expandedDir) + log.Info("Processing directory", slog.String("directory", expandedDir)) // Run lint for this directory as a separate execution if err := runLint(expandedDir); err != nil { - logger.ErrorF("Error processing directory %s: %v", expandedDir, err) + log.Error("Error processing directory", slog.String("directory", expandedDir), log.Err(err)) hasErrors = true // Continue processing other directories even if one fails } diff --git a/go.mod b/go.mod index b9554c23..0365f3d4 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/Masterminds/semver/v3 v3.3.1 github.com/Masterminds/sprig/v3 v3.3.0 github.com/bmatcuk/doublestar v1.3.4 + github.com/deckhouse/deckhouse/pkg/log v0.1.1 github.com/fatih/color v1.16.0 github.com/flant/addon-operator v1.5.0 github.com/go-openapi/spec v0.21.0 @@ -50,6 +51,7 @@ require ( github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.1 // indirect github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect github.com/AzureAD/microsoft-authentication-library-for-go v1.3.2 // indirect + github.com/DataDog/gostackparse v0.7.0 // indirect github.com/Masterminds/goutils v1.1.1 // indirect github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b // indirect diff --git a/go.sum b/go.sum index 6d788894..1f4a6e45 100644 --- a/go.sum +++ b/go.sum @@ -28,6 +28,8 @@ github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/Code-Hex/go-generics-cache v1.5.1 h1:6vhZGc5M7Y/YD8cIUcY8kcuQLB4cHR7U+0KMqAA0KcU= github.com/Code-Hex/go-generics-cache v1.5.1/go.mod h1:qxcC9kRVrct9rHeiYpFWSoW1vxyillCVzX13KZG8dl4= +github.com/DataDog/gostackparse v0.7.0 h1:i7dLkXHvYzHV308hnkvVGDL3BR4FWl7IsXNPz/IGQh4= +github.com/DataDog/gostackparse v0.7.0/go.mod h1:lTfqcJKqS9KnXQGnyQMCugq3u1FP6UZMfWR0aitKFMM= github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver/v3 v3.3.1 h1:QtNSWtVZ3nBfk8mAOu/B6v7FMJ+NHTIgUPi7rj+4nv4= @@ -63,6 +65,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/deckhouse/deckhouse/pkg/log v0.1.1 h1:qHpMyj9coob+VfP3Qv+eIBa0pXFLn1FFRJztyryILB0= +github.com/deckhouse/deckhouse/pkg/log v0.1.1/go.mod h1:pbAxTSDcPmwyl3wwKDcEB3qdxHnRxqTV+J0K+sha8bw= github.com/dennwc/varint v1.0.0 h1:kGNFFSSw8ToIy3obO/kKr8U9GZYUAxQEVuix4zfDWzE= github.com/dennwc/varint v1.0.0/go.mod h1:hnItb35rvZvJrbTALZtY/iQfDs48JKRG1RPpgziApxA= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= diff --git a/internal/bootstrap/bootstrap.go b/internal/bootstrap/bootstrap.go index 642be69f..b27855fa 100644 --- a/internal/bootstrap/bootstrap.go +++ b/internal/bootstrap/bootstrap.go @@ -21,6 +21,7 @@ import ( "context" "fmt" "io" + "log/slog" "net/http" "os" "path/filepath" @@ -30,8 +31,9 @@ import ( "github.com/iancoleman/strcase" "gopkg.in/yaml.v3" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/fsutils" - "github.com/deckhouse/dmt/internal/logger" ) const ( @@ -61,7 +63,7 @@ type BootstrapConfig struct { // RunBootstrap initializes a new module with the given configuration func RunBootstrap(config BootstrapConfig) error { - logger.InfoF("Bootstrap type: %s", config.RepositoryType) + log.Info("Bootstrap type", slog.String("type", config.RepositoryType)) // if config.Directory does not exist, create it if _, err := os.Stat(config.Directory); os.IsNotExist(err) { @@ -75,7 +77,7 @@ func RunBootstrap(config BootstrapConfig) error { return fmt.Errorf("failed to get absolute directory path: %w", err) } - logger.InfoF("Using directory: %s", absDirectory) + log.Info("Using directory", slog.String("directory", absDirectory)) // Check if directory is empty if err := checkDirectoryEmpty(absDirectory); err != nil { @@ -114,7 +116,7 @@ func RunBootstrap(config BootstrapConfig) error { } } - logger.InfoF("Bootstrap completed successfully") + log.Info("Bootstrap completed successfully") return nil } @@ -145,7 +147,7 @@ func checkDirectoryEmpty(absDirectory string) error { return fmt.Errorf("directory is not empty. Please run bootstrap in an empty directory") } - logger.DebugF("Directory is empty, proceeding with bootstrap") + log.Debug("Directory is empty, proceeding with bootstrap") return nil } @@ -266,7 +268,7 @@ func downloadAndExtractTemplate(repositoryURL, directory string) error { // downloadFile downloads a file from URL to local path with timeout func downloadFile(url, targetPath string) error { - logger.InfoF("Downloading template from: %s", url) + log.Info("Downloading template", slog.String("url", url)) ctx, cancel := context.WithTimeout(context.Background(), downloadTimeout) defer cancel() @@ -299,13 +301,13 @@ func downloadFile(url, targetPath string) error { return fmt.Errorf("failed to write file: %w", err) } - logger.InfoF("Template downloaded successfully") + log.Info("Template downloaded successfully") return nil } // extractZip extracts a zip file to the specified directory func extractZip(zipPath, extractDir string) error { - logger.DebugF("Extracting template archive") + log.Debug("Extracting template archive") reader, err := zip.OpenReader(zipPath) if err != nil { @@ -380,7 +382,7 @@ func extractZip(zipPath, extractDir string) error { } } - logger.DebugF("Template extracted successfully") + log.Debug("Template extracted successfully") return nil } @@ -418,7 +420,7 @@ func moveExtractedContent(tempDir, directory string) error { } } - logger.DebugF("Template files moved to current directory") + log.Debug("Template files moved to current directory") return nil } diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 1298191e..9ff010d9 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -19,6 +19,7 @@ package engine import ( "errors" "fmt" + "log/slog" "path" "path/filepath" "regexp" @@ -29,7 +30,7 @@ import ( "helm.sh/helm/v3/pkg/chart" "helm.sh/helm/v3/pkg/chartutil" - "github.com/deckhouse/dmt/internal/logger" + "github.com/deckhouse/deckhouse/pkg/log" ) // Engine is an implementation of the Helm rendering implementation for templates. @@ -177,7 +178,7 @@ func (e Engine) initFuncMap(t *template.Template) { if val == nil { if e.LintMode { // Don't fail on missing required values when linting - logger.WarnF("[WARNING] Missing required value: %s", warn) + log.Warn("[WARNING] Missing required value", slog.String("value", warn)) return "", nil } return val, errors.New(warnWrap(warn)) @@ -185,7 +186,7 @@ func (e Engine) initFuncMap(t *template.Template) { if val == "" { if e.LintMode { // Don't fail on missing required values when linting - logger.ErrorF("[ERROR] Missing required value: %s", warn) + log.Error("[ERROR] Missing required value", slog.String("value", warn)) return "", nil } return val, errors.New(warnWrap(warn)) @@ -198,7 +199,7 @@ func (e Engine) initFuncMap(t *template.Template) { funcMap["fail"] = func(msg string) (string, error) { if e.LintMode { // Don't fail when linting - logger.WarnF("[WARNING] Fail: %s", msg) + log.Warn("[WARNING] Fail", slog.String("message", msg)) return "", nil } return "", errors.New(warnWrap(msg)) @@ -287,7 +288,7 @@ func (e Engine) render(tpls map[string]renderable) (rendered map[string]string, } if e.LintMode && isRecoverableNilError { - logger.ErrorF("[LINT] Template %s encountered a nil pointer access during execution: %v. Using partially rendered output.", filename, executeErr) + log.Error("[LINT] Template encountered a nil pointer access during execution. Using partially rendered output", slog.String("template", filename), slog.Any("error", executeErr)) rendered[filename] = getRenderedContent(&buf) } else { // For other errors, or if not in LintMode, this is a hard error. diff --git a/internal/flags/flags.go b/internal/flags/flags.go index 055a53f8..4f2b53c3 100644 --- a/internal/flags/flags.go +++ b/internal/flags/flags.go @@ -19,7 +19,7 @@ package flags import ( "github.com/spf13/pflag" - "github.com/deckhouse/dmt/internal/logger" + "github.com/deckhouse/deckhouse/pkg/log" ) const ( @@ -72,27 +72,27 @@ func InitLintFlagSet() *pflag.FlagSet { lint.BoolVarP(&HideWarnings, "hide-warnings", "", false, "hide warnings") err := lint.MarkHidden("hide-warnings") if err != nil { - logger.ErrorF("mark hidden flag 'hide-warnings' is failed") + log.Error("mark hidden flag 'hide-warnings' is failed") } // make path absolute lint.BoolVarP(&AbsPath, "abs-path", "", false, "make paths absolute") err = lint.MarkHidden("abs-path") if err != nil { - logger.ErrorF("mark hidden flag 'abs-path' is failed") + log.Error("mark hidden flag 'abs-path' is failed") } // show ignored errors lint.BoolVarP(&ShowIgnored, "show-ignored", "", false, "show ignored errors") err = lint.MarkHidden("show-ignored") if err != nil { - logger.ErrorF("mark hidden flag 'show-ignored' is failed") + log.Error("mark hidden flag 'show-ignored' is failed") } lint.BoolVarP(&ShowDocumentation, "doc", "", false, "show documentation links") err = lint.MarkHidden("doc") if err != nil { - logger.ErrorF("mark hidden flag 'doc' is failed") + log.Error("mark hidden flag 'doc' is failed") } return lint diff --git a/internal/logger/logger.go b/internal/logger/logger.go deleted file mode 100644 index 1fa40e28..00000000 --- a/internal/logger/logger.go +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright 2025 Flant JSC - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package logger - -import ( - "fmt" - "io" - "log" - "log/slog" - "os" -) - -const ( - DebugLogLevel = "DEBUG" - InfoLogLevel = "INFO" - WarnLogLevel = "WARN" - ErrorLogLevel = "ERROR" -) - -func InitLogger(w io.Writer, logLevel string) { - lvl := new(slog.LevelVar) - lvl.Set(slog.LevelInfo) - - logger := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{Level: lvl})) - - switch logLevel { - case DebugLogLevel: - lvl.Set(slog.LevelDebug) - case InfoLogLevel: - lvl.Set(slog.LevelInfo) - case WarnLogLevel: - lvl.Set(slog.LevelWarn) - case ErrorLogLevel: - lvl.Set(slog.LevelError) - } - - slog.SetDefault(logger) - log.SetOutput(io.Discard) -} - -// Deprecated: use slog directly instead of these wrapper functions -func DebugF(format string, a ...any) { - slog.Debug( - fmt.Sprintf(format, a...)) -} - -// Deprecated: use slog directly instead of these wrapper functions -func InfoF(format string, a ...any) { - slog.Info( - fmt.Sprintf(format, a...)) -} - -// Deprecated: use slog directly instead of these wrapper functions -func WarnF(format string, a ...any) { - slog.Warn( - fmt.Sprintf(format, a...)) -} - -// Deprecated: use slog directly instead of these wrapper functions -func ErrorF(format string, a ...any) { - slog.Error( - fmt.Sprintf(format, a...)) -} - -func CheckErr(msg any) { - if msg != nil { - slog.Error( - fmt.Sprintf("Error: %s", msg)) - os.Exit(1) - } -} diff --git a/internal/logger/logger_test.go b/internal/logger/logger_test.go deleted file mode 100644 index c3f3669d..00000000 --- a/internal/logger/logger_test.go +++ /dev/null @@ -1,79 +0,0 @@ -/* -Copyright 2025 Flant JSC - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package logger - -import ( - "bytes" - "log/slog" - "testing" -) - -func TestInitLogger(t *testing.T) { - tests := []struct { - name string - logLevel string - expected string - }{ - {"DebugLevel", DebugLogLevel, "DEBUG"}, - {"InfoLevel", InfoLogLevel, "INFO"}, - {"WarnLevel", WarnLogLevel, "WARN"}, - {"ErrorLevel", ErrorLogLevel, "ERROR"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - buf := bytes.Buffer{} - InitLogger(&buf, tt.logLevel) - slog.Debug("test debug") - slog.Info("test info") - slog.Warn("test warn") - slog.Error("test error") - - if !bytes.Contains(buf.Bytes(), []byte(tt.expected)) { - t.Errorf("expected log level %s not found in output", tt.expected) - } - buf.Reset() - }) - } -} - -func TestLogFunctions(t *testing.T) { - var buf bytes.Buffer - InitLogger(&buf, DebugLogLevel) - - DebugF("Debug message: %d", 1) - InfoF("Info message: %s", "test") - WarnF("Warn message") - ErrorF("Error message") - - logOutput := buf.String() - tests := []struct { - name string - expected string - }{ - {"DebugMessage", "Debug message: 1"}, - {"InfoMessage", "Info message: test"}, - {"WarnMessage", "Warn message"}, - {"ErrorMessage", "Error message"}, - } - - for _, tt := range tests { - if !bytes.Contains([]byte(logOutput), []byte(tt.expected)) { - t.Errorf("expected log message %q not found in output", tt.expected) - } - } -} diff --git a/internal/manager/manager.go b/internal/manager/manager.go index edf8121b..8038c941 100644 --- a/internal/manager/manager.go +++ b/internal/manager/manager.go @@ -20,6 +20,7 @@ import ( "bytes" "cmp" "fmt" + "log/slog" "os" "path/filepath" "slices" @@ -32,9 +33,10 @@ import ( "github.com/mitchellh/go-wordwrap" "helm.sh/helm/v3/pkg/chartutil" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/flags" "github.com/deckhouse/dmt/internal/fsutils" - "github.com/deckhouse/dmt/internal/logger" "github.com/deckhouse/dmt/internal/metrics" "github.com/deckhouse/dmt/internal/module" "github.com/deckhouse/dmt/internal/values" @@ -94,24 +96,24 @@ func NewManager(dir string, rootConfig *config.RootConfig) *Manager { func (m *Manager) initManager(dir string) *Manager { paths, err := getModulePaths(dir) if err != nil { - logger.ErrorF("Error getting module paths: %v", err) + log.Error("Error getting module paths", log.Err(err)) return m } vals, err := decodeValuesFile(flags.ValuesFile) if err != nil { - logger.ErrorF("Failed to decode values file: %v", err) + log.Error("Failed to decode values file", log.Err(err)) } globalValues, err := values.GetGlobalValues(getRootDirectory(dir)) if err != nil { - logger.ErrorF("Failed to get global values: %v", err) + log.Error("Failed to get global values", log.Err(err)) return m } errorList := m.errors.WithLinterID("manager") for i := range paths { moduleName := filepath.Base(paths[i]) - logger.DebugF("Found `%s` module", moduleName) + log.Debug("Found module", slog.String("module", moduleName)) if err := m.validateModule(paths[i]); err != nil { // linting errors are already logged continue @@ -128,7 +130,7 @@ func (m *Manager) initManager(dir string) *Manager { m.Modules = append(m.Modules, mdl) } - logger.InfoF("Found %d modules", len(m.Modules)) + log.Info("Found modules", slog.Int("count", len(m.Modules))) return m } @@ -160,14 +162,14 @@ func (m *Manager) Run() { wg.Done() }() - logger.InfoF("Run linters for `%s` module", module.GetName()) + log.Info("Run linters for module", slog.String("module", module.GetName())) for _, linter := range getLintersForModule(module.GetModuleConfig(), m.errors) { if flags.LinterName != "" && linter.Name() != flags.LinterName { continue } - logger.DebugF("Running linter `%s` on module `%s`", linter.Name(), module.GetName()) + log.Debug("Running linter", slog.String("linter", linter.Name()), slog.String("module", module.GetName())) linter.Run(module) } diff --git a/internal/metrics/repository.go b/internal/metrics/repository.go index f950d2ba..865af618 100644 --- a/internal/metrics/repository.go +++ b/internal/metrics/repository.go @@ -22,8 +22,9 @@ import ( "gopkg.in/ini.v1" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/fsutils" - "github.com/deckhouse/dmt/internal/logger" ) func getRepositoryAddress(dir string) string { @@ -34,13 +35,13 @@ func getRepositoryAddress(dir string) string { cfg, err := ini.Load(configFile) if err != nil { - logger.ErrorF("Failed to load config file: %v", err) + log.Error("Failed to load config file", log.Err(err)) return "" } sec, err := cfg.GetSection("remote \"origin\"") if err != nil { - logger.ErrorF("Failed to get remote \"origin\": %v", err) + log.Error("Failed to get remote origin", log.Err(err)) return "" } diff --git a/internal/metrics/service.go b/internal/metrics/service.go index 16deee30..0d7c86ef 100644 --- a/internal/metrics/service.go +++ b/internal/metrics/service.go @@ -19,7 +19,8 @@ package metrics import ( "context" - "github.com/deckhouse/dmt/internal/logger" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/promremote" ) @@ -61,6 +62,6 @@ func (p *PrometheusMetricsService) Send(ctx context.Context) { promremote.WriteOptions{}, ) if err != nil { - logger.ErrorF("error in sending metrics: %v", err) + log.Error("error in sending metrics", log.Err(err)) } } diff --git a/internal/values/values.go b/internal/values/values.go index 92158dee..24b181b1 100644 --- a/internal/values/values.go +++ b/internal/values/values.go @@ -3,6 +3,7 @@ package values import ( _ "embed" "fmt" + "log/slog" "os" "path/filepath" @@ -12,7 +13,8 @@ import ( "helm.sh/helm/v3/pkg/chartutil" "sigs.k8s.io/yaml" - "github.com/deckhouse/dmt/internal/logger" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/module/schema" ) @@ -92,7 +94,7 @@ func GetGlobalValues(rootDir string) (*spec.Schema, error) { if err != nil { return nil, err } - logger.InfoF("Using global values from `%s` directory", rootDir) + log.Info("Using global values", slog.String("directory", rootDir)) configBytes = configBytesT valuesBytes = valuesBytesT } diff --git a/internal/werf/werf.go b/internal/werf/werf.go index f5a586a6..6450bb6a 100644 --- a/internal/werf/werf.go +++ b/internal/werf/werf.go @@ -22,6 +22,7 @@ import ( "crypto/rand" "errors" "fmt" + "log/slog" "math/big" "os" "path/filepath" @@ -32,8 +33,9 @@ import ( "github.com/Masterminds/sprig/v3" "sigs.k8s.io/yaml" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/fsutils" - "github.com/deckhouse/dmt/internal/logger" ) const ( @@ -84,7 +86,7 @@ func GetWerfConfig(dir string) (string, error) { func getRootWerfFile(dir string) string { absPath, err := filepath.Abs(dir) if err != nil { - logger.WarnF("Can't make abs path for %q: %s", dir, err) + log.Warn("Can't make abs path", slog.String("path", dir), log.Err(err)) absPath = filepath.Clean(dir) } diff --git a/pkg/config/loader.go b/pkg/config/loader.go index 499e3a45..7043dd45 100644 --- a/pkg/config/loader.go +++ b/pkg/config/loader.go @@ -19,6 +19,7 @@ package config import ( "errors" "fmt" + "log/slog" "os" "path/filepath" "slices" @@ -27,8 +28,9 @@ import ( "github.com/mitchellh/mapstructure" "github.com/spf13/viper" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/fsutils" - "github.com/deckhouse/dmt/internal/logger" ) type LoaderOptions struct { @@ -69,7 +71,7 @@ func (l *Loader) setConfigFile() error { configSearchPaths := l.getConfigSearchPaths() - logger.DebugF("Config search paths: %s", configSearchPaths) + log.Debug("Config search paths", slog.Any("paths", configSearchPaths)) for _, p := range configSearchPaths { l.viper.AddConfigPath(p) @@ -86,7 +88,7 @@ func (l *Loader) getConfigSearchPaths() []string { absPath, err := filepath.Abs(firstArg) if err != nil { - logger.WarnF("Can't make abs path for %q: %s", firstArg, err) + log.Warn("Can't make abs path", slog.String("path", firstArg), log.Err(err)) absPath = filepath.Clean(firstArg) } @@ -114,7 +116,7 @@ func (l *Loader) getConfigSearchPaths() []string { // find home directory for global config if home, err := homedir.Dir(); err != nil { - logger.WarnF("Can't get user's home directory: %v", err) + log.Warn("Can't get user's home directory", log.Err(err)) } else if !slices.Contains(searchPaths, home) { searchPaths = append(searchPaths, home) } @@ -159,10 +161,10 @@ func (l *Loader) setConfigDir() error { if usedConfigFile == os.Stdin.Name() { usedConfigFile = "" - logger.InfoF("Reading config file stdin") + log.Info("Reading config file stdin") } - logger.DebugF("Used config file %s", usedConfigFile) + log.Debug("Used config file", slog.String("file", usedConfigFile)) return nil } diff --git a/pkg/linters/module/rules/license.go b/pkg/linters/module/rules/license.go index 56e48daf..bc718371 100644 --- a/pkg/linters/module/rules/license.go +++ b/pkg/linters/module/rules/license.go @@ -18,11 +18,13 @@ package rules import ( "errors" + "log/slog" "os" "regexp" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/fsutils" - "github.com/deckhouse/dmt/internal/logger" "github.com/deckhouse/dmt/internal/module" "github.com/deckhouse/dmt/pkg" pkgerrors "github.com/deckhouse/dmt/pkg/errors" @@ -77,7 +79,7 @@ func (r *LicenseRule) CheckFiles(mod *module.Module, errorList *pkgerrors.LintRu _, parseErr := parser.ParseFile(fileName) if errors.Is(parseErr, ErrUnsupportedFileType) { - logger.DebugF("Skipping unsupported file type: %s", name) + log.Debug("Skipping unsupported file type", slog.String("file", name)) continue } @@ -91,7 +93,7 @@ func (r *LicenseRule) CheckFiles(mod *module.Module, errorList *pkgerrors.LintRu func filterFiles(rootPath, path string) bool { f, err := os.Stat(path) if err != nil { - logger.DebugF("Error getting file info: %v", err) + log.Debug("Error getting file info", log.Err(err)) return false } if f.IsDir() { diff --git a/pkg/linters/module/rules/module_yaml.go b/pkg/linters/module/rules/module_yaml.go index b0419832..5b218a6a 100644 --- a/pkg/linters/module/rules/module_yaml.go +++ b/pkg/linters/module/rules/module_yaml.go @@ -30,8 +30,9 @@ import ( "k8s.io/utils/ptr" "sigs.k8s.io/yaml" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/fsutils" - "github.com/deckhouse/dmt/internal/logger" "github.com/deckhouse/dmt/pkg" "github.com/deckhouse/dmt/pkg/errors" ) @@ -135,13 +136,13 @@ func getModuleNameFromRepository(dir string) string { cfg, err := ini.Load(configFile) if err != nil { - logger.ErrorF("Failed to load config file: %v", err) + log.Error("Failed to load config file", log.Err(err)) return "" } sec, err := cfg.GetSection("remote \"origin\"") if err != nil { - logger.ErrorF("Failed to get remote \"origin\": %v", err) + log.Error("Failed to get remote origin", log.Err(err)) return "" } diff --git a/pkg/linters/templates/rules/ingress.go b/pkg/linters/templates/rules/ingress.go index b305c172..27afce29 100644 --- a/pkg/linters/templates/rules/ingress.go +++ b/pkg/linters/templates/rules/ingress.go @@ -17,12 +17,14 @@ limitations under the License. package rules import ( + "log/slog" "strings" v1 "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/runtime" - "github.com/deckhouse/dmt/internal/logger" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/storage" "github.com/deckhouse/dmt/pkg" "github.com/deckhouse/dmt/pkg/errors" @@ -57,7 +59,7 @@ func (r *IngressRule) CheckSnippetsRule(object storage.StoreObject, errorList *e } if !r.Enabled(object.Unstructured.GetKind(), object.Unstructured.GetName()) { - logger.InfoF("⚠️ Skip Ingress %q due to exclusion rule.\n", object.Unstructured.GetName()) + log.Info("⚠️ Skip Ingress due to exclusion rule", slog.String("name", object.Unstructured.GetName())) return } diff --git a/pkg/linters/templates/rules/registry.go b/pkg/linters/templates/rules/registry.go index 7d7c6d63..74c815bc 100644 --- a/pkg/linters/templates/rules/registry.go +++ b/pkg/linters/templates/rules/registry.go @@ -25,8 +25,9 @@ import ( "gopkg.in/ini.v1" + "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/dmt/internal/fsutils" - "github.com/deckhouse/dmt/internal/logger" "github.com/deckhouse/dmt/internal/module" "github.com/deckhouse/dmt/pkg" "github.com/deckhouse/dmt/pkg/errors" @@ -95,13 +96,13 @@ func getModuleNameFromRepository(dir string) string { cfg, err := ini.Load(configFile) if err != nil { - logger.ErrorF("Failed to load config file: %v", err) + log.Error("Failed to load config file", log.Err(err)) return "" } sec, err := cfg.GetSection("remote \"origin\"") if err != nil { - logger.ErrorF("Failed to get remote \"origin\": %v", err) + log.Error("Failed to get remote origin", log.Err(err)) return "" }