Skip to content

Commit

Permalink
refactor: replace zap with slog (#6466)
Browse files Browse the repository at this point in the history
Signed-off-by: knqyf263 <knqyf263@gmail.com>
Co-authored-by: Nikita Pivkin <nikita.pivkin@smartforce.io>
Co-authored-by: simar7 <1254783+simar7@users.noreply.github.com>
  • Loading branch information
3 people committed Apr 11, 2024
1 parent 336c47e commit 94d6e8c
Show file tree
Hide file tree
Showing 164 changed files with 1,657 additions and 884 deletions.
2 changes: 1 addition & 1 deletion cmd/trivy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (

func main() {
if err := run(); err != nil {
log.Fatal(err)
log.Fatal("Fatal error", log.Err(err))
}
}

Expand Down
4 changes: 2 additions & 2 deletions magefiles/cloud_actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,10 +206,10 @@ func main() {

// GenAllowedActions generates the list of valid actions for wildcard support
func GenAllowedActions() error {
log.Logger.Info("Start parsing actions")
log.Info("Start parsing actions")
startTime := time.Now()
defer func() {
log.Logger.Infof("Parsing is completed. Duration %fs\n", time.Since(startTime).Seconds())
log.Info("Parsing is completed", log.Duration(time.Since(startTime).Seconds()))
}()

doc, err := htmlquery.LoadURL(serviceActionReferencesURL)
Expand Down
2 changes: 1 addition & 1 deletion magefiles/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ func main() {
cmd := commands.NewApp()
cmd.DisableAutoGenTag = true
if err := doc.GenMarkdownTree(cmd, "./docs/docs/references/configuration/cli"); err != nil {
log.Fatal(err)
log.Fatal("Fatal error", log.Err(err))
}
}
2 changes: 1 addition & 1 deletion pkg/attestation/sbom/rekor.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (r *Rekor) RetrieveSBOM(ctx context.Context, digest string) ([]byte, error)
return nil, ErrNoSBOMAttestation
}

log.Logger.Debugf("Found matching Rekor entries: %s", entryIDs)
log.Debug("Found matching Rekor entries", log.Any("entry_ids", entryIDs))

for _, ids := range lo.Chunk[rekor.EntryID](entryIDs, rekor.MaxGetEntriesLimit) {
entries, err := r.client.GetEntries(ctx, ids)
Expand Down
2 changes: 1 addition & 1 deletion pkg/attestation/sbom/rekor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func TestRekor_RetrieveSBOM(t *testing.T) {
},
}

require.NoError(t, log.InitLogger(false, true))
log.InitLogger(false, true)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ts := rekortest.NewServer(t)
Expand Down
27 changes: 15 additions & 12 deletions pkg/cloud/aws/commands/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
var allSupportedServicesFunc = awsScanner.AllSupportedServices

func getAccountIDAndRegion(ctx context.Context, region, endpoint string) (string, string, error) {
log.Logger.Debug("Looking for AWS credentials provider...")
log.DebugContext(ctx, "Looking for AWS credentials provider...")

cfg, err := config.LoadDefaultAWSConfig(ctx, region, endpoint)
if err != nil {
Expand All @@ -32,15 +32,15 @@ func getAccountIDAndRegion(ctx context.Context, region, endpoint string) (string

svc := sts.NewFromConfig(cfg)

log.Logger.Debug("Looking up AWS caller identity...")
log.DebugContext(ctx, "Looking up AWS caller identity...")
result, err := svc.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{})
if err != nil {
return "", "", xerrors.Errorf("failed to discover AWS caller identity: %w", err)
}
if result.Account == nil {
return "", "", xerrors.Errorf("missing account id for aws account")
}
log.Logger.Debugf("Verified AWS credentials for account %s!", *result.Account)
log.DebugContext(ctx, "Verified AWS credentials for account!", log.String("account", *result.Account))
return *result.Account, cfg.Region, nil
}

Expand Down Expand Up @@ -85,22 +85,22 @@ func processOptions(ctx context.Context, opt *flag.Options) error {
}
}

err := filterServices(opt)
err := filterServices(ctx, opt)
if err != nil {
return err
}

log.Logger.Debug("scanning services: ", opt.Services)
log.DebugContext(ctx, "Scanning services", log.Any("services", opt.Services))
return nil
}

func filterServices(opt *flag.Options) error {
func filterServices(ctx context.Context, opt *flag.Options) error {
switch {
case len(opt.Services) == 0 && len(opt.SkipServices) == 0:
log.Logger.Debug("No service(s) specified, scanning all services...")
log.DebugContext(ctx, "No service(s) specified, scanning all services...")
opt.Services = allSupportedServicesFunc()
case len(opt.SkipServices) > 0:
log.Logger.Debug("excluding services: ", opt.SkipServices)
log.DebugContext(ctx, "Excluding services", log.Any("services", opt.SkipServices))
for _, s := range allSupportedServicesFunc() {
if slices.Contains(opt.SkipServices, s) {
continue
Expand All @@ -110,7 +110,8 @@ func filterServices(opt *flag.Options) error {
}
}
case len(opt.Services) > 0:
log.Logger.Debugf("Specific services were requested: [%s]...", strings.Join(opt.Services, ", "))
log.DebugContext(ctx, "Specific services were requested...",
log.String("services", strings.Join(opt.Services, ", ")))
for _, service := range opt.Services {
var found bool
supported := allSupportedServicesFunc()
Expand All @@ -132,10 +133,12 @@ func Run(ctx context.Context, opt flag.Options) error {
ctx, cancel := context.WithTimeout(ctx, opt.GlobalOptions.Timeout)
defer cancel()

ctx = log.WithContextPrefix(ctx, "aws")

var err error
defer func() {
if errors.Is(err, context.DeadlineExceeded) {
log.Logger.Warn("Increase --timeout value")
log.Warn("Increase --timeout value")
}
}()

Expand All @@ -148,14 +151,14 @@ func Run(ctx context.Context, opt flag.Options) error {
var aerr errs.AdapterError
if errors.As(err, &aerr) {
for _, e := range aerr.Errors() {
log.Logger.Warnf("Adapter error: %s", e)
log.WarnContext(ctx, "Adapter error", log.Err(e))
}
} else {
return xerrors.Errorf("aws scan error: %w", err)
}
}

log.Logger.Debug("Writing report to output...")
log.DebugContext(ctx, "Writing report to output...")

res := results.GetFailed()
if opt.MisconfOptions.IncludeNonFailures {
Expand Down
13 changes: 8 additions & 5 deletions pkg/cloud/aws/scanner/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,21 @@ import (
)

type AWSScanner struct {
logger *log.Logger
}

func NewScanner() *AWSScanner {
return &AWSScanner{}
return &AWSScanner{
logger: log.WithPrefix("aws"),
}
}

func (s *AWSScanner) Scan(ctx context.Context, option flag.Options) (scan.Results, bool, error) {

awsCache := cache.New(option.CacheDir, option.MaxCacheAge, option.Account, option.Region)
included, missing := awsCache.ListServices(option.Services)

prefixedLogger := &log.PrefixedLogger{Name: "aws"}
prefixedLogger := log.NewWriteLogger(log.WithPrefix("aws"))

var scannerOpts []options.ScannerOption
if !option.NoProgress {
Expand Down Expand Up @@ -72,10 +75,10 @@ func (s *AWSScanner) Scan(ctx context.Context, option flag.Options) (scan.Result
downloadedPolicyPaths, err = operation.InitBuiltinPolicies(context.Background(), option.CacheDir, option.Quiet, option.SkipPolicyUpdate, option.MisconfOptions.PolicyBundleRepository, option.RegistryOpts())
if err != nil {
if !option.SkipPolicyUpdate {
log.Logger.Errorf("Falling back to embedded policies: %s", err)
s.logger.Error("Falling back to embedded policies", log.Err(err))
}
} else {
log.Logger.Debug("Policies successfully loaded from disk")
s.logger.Debug("Policies successfully loaded from disk")
policyPaths = append(policyPaths, downloadedPolicyPaths...)
scannerOpts = append(scannerOpts,
options.ScannerWithEmbeddedPolicies(false),
Expand All @@ -95,7 +98,7 @@ func (s *AWSScanner) Scan(ctx context.Context, option flag.Options) (scan.Result

dataFS, dataPaths, err := misconf.CreateDataFS(option.RegoOptions.DataPaths)
if err != nil {
log.Logger.Errorf("Could not load config data: %s", err)
s.logger.Error("Could not load config data", err)
}
scannerOpts = append(scannerOpts,
options.ScannerWithDataDirs(dataPaths...),
Expand Down
16 changes: 7 additions & 9 deletions pkg/commands/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func loadPluginCommands() []*cobra.Command {
var commands []*cobra.Command
plugins, err := plugin.LoadAll()
if err != nil {
log.Logger.Debugf("no plugins were loaded")
log.Debug("No plugins loaded")
return nil
}
for _, p := range plugins {
Expand Down Expand Up @@ -142,12 +142,12 @@ func initConfig(configFile string) error {
viper.SetConfigType("yaml")
if err := viper.ReadInConfig(); err != nil {
if errors.Is(err, os.ErrNotExist) {
log.Logger.Debugf("config file %q not found", configFile)
log.Debug("Config file not found", log.String("file_path", configFile))
return nil
}
return xerrors.Errorf("config file %q loading error: %s", configFile, err)
}
log.Logger.Infof("Loaded %s", configFile)
log.Info("Loaded", log.String("file_path", configFile))
return nil
}

Expand Down Expand Up @@ -196,9 +196,7 @@ func NewRootCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command {
}

// Initialize logger
if err := log.InitLogger(globalOptions.Debug, globalOptions.Quiet); err != nil {
return err
}
log.InitLogger(globalOptions.Debug, globalOptions.Quiet)

return nil
},
Expand Down Expand Up @@ -570,7 +568,7 @@ func NewClientCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command {
return validateArgs(cmd, args)
},
RunE: func(cmd *cobra.Command, args []string) error {
log.Logger.Warn("'client' subcommand is deprecated now. See https://github.com/aquasecurity/trivy/discussions/2119")
log.Warn("'client' subcommand is deprecated now. See https://github.com/aquasecurity/trivy/discussions/2119")

if err := clientFlags.Bind(cmd); err != nil {
return xerrors.Errorf("flag bind error: %w", err)
Expand Down Expand Up @@ -1040,7 +1038,7 @@ The following services are supported:
}
if opts.Timeout < time.Hour {
opts.Timeout = time.Hour
log.Logger.Debug("Timeout is set to less than 1 hour - upgrading to 1 hour for this command.")
log.Info("Timeout is set to less than 1 hour - upgrading to 1 hour for this command.")
}
return awscommands.Run(cmd.Context(), opts)
},
Expand Down Expand Up @@ -1106,7 +1104,7 @@ func NewVMCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command {
}
if options.Timeout < time.Minute*30 {
options.Timeout = time.Minute * 30
log.Logger.Debug("Timeout is set to less than 30 min - upgrading to 30 min for this command.")
log.Info("Timeout is set to less than 30 min - upgrading to 30 min for this command.")
}
return artifact.Run(cmd.Context(), options, artifact.TargetVM)
},
Expand Down
33 changes: 17 additions & 16 deletions pkg/commands/artifact/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ func (r *runner) initCache(opts flag.Options) error {
if err != nil {
return xerrors.Errorf("unable to initialize the cache: %w", err)
}
log.Logger.Debugf("cache dir: %s", fsutils.CacheDir())
log.Debug("Cache dir", log.String("dir", fsutils.CacheDir()))

if opts.Reset {
defer cacheClient.Close()
Expand Down Expand Up @@ -400,12 +400,12 @@ func Run(ctx context.Context, opts flag.Options, targetKind TargetKind) (err err

defer func() {
if errors.Is(err, context.DeadlineExceeded) {
log.Logger.Warn("Increase --timeout value")
log.Warn("Increase --timeout value")
}
}()

if opts.GenerateDefaultConfig {
log.Logger.Info("Writing the default config to trivy-default.yaml...")
log.Info("Writing the default config to trivy-default.yaml...")
return viper.SafeWriteConfigAs("trivy-default.yaml")
}

Expand Down Expand Up @@ -484,7 +484,8 @@ func disabledAnalyzers(opts flag.Options) []analyzer.Type {
// Filter only enabled misconfiguration scanners
ma, err := filterMisconfigAnalyzers(opts.MisconfigScanners, analyzer.TypeConfigFiles)
if err != nil {
log.Logger.Errorf("Invalid misconfig scanners specified: %s defaulting to use all misconfig scanners", opts.MisconfigScanners)
log.Error("Invalid misconfiguration scanners specified, defaulting to use all misconfig scanners",
log.Any("scanners", opts.MisconfigScanners))
} else {
analyzers = append(analyzers, ma...)
}
Expand Down Expand Up @@ -528,7 +529,7 @@ func filterMisconfigAnalyzers(included, all []analyzer.Type) ([]analyzer.Type, e
return nil, xerrors.Errorf("invalid misconfiguration scanner specified %s valid scanners: %s", missing, all)
}

log.Logger.Debugf("Enabling misconfiguration scanners: %s", included)
log.Debug("Enabling misconfiguration scanners", log.Any("scanners", included))
return lo.Without(all, included...), nil
}

Expand Down Expand Up @@ -569,28 +570,28 @@ func initScannerConfig(opts flag.Options, cacheClient cache.Cache) (ScannerConfi
}

if len(opts.ImageConfigScanners) != 0 {
log.Logger.Infof("Container image config scanners: %q", opts.ImageConfigScanners)
log.Info("Container image config scanners", log.Any("scanners", opts.ImageConfigScanners))
}

if opts.Scanners.Enabled(types.VulnerabilityScanner) {
log.Logger.Info("Vulnerability scanning is enabled")
log.Logger.Debugf("Vulnerability type: %s", scanOptions.VulnType)
log.Info("Vulnerability scanning is enabled")
log.Debug("Vulnerability type", log.Any("type", scanOptions.VulnType))
}

// ScannerOption is filled only when config scanning is enabled.
var configScannerOptions misconf.ScannerOption
if opts.Scanners.Enabled(types.MisconfigScanner) || opts.ImageConfigScanners.Enabled(types.MisconfigScanner) {
log.Logger.Info("Misconfiguration scanning is enabled")
log.Info("Misconfiguration scanning is enabled")

var downloadedPolicyPaths []string
var disableEmbedded bool
downloadedPolicyPaths, err := operation.InitBuiltinPolicies(context.Background(), opts.CacheDir, opts.Quiet, opts.SkipPolicyUpdate, opts.MisconfOptions.PolicyBundleRepository, opts.RegistryOpts())
if err != nil {
if !opts.SkipPolicyUpdate {
log.Logger.Errorf("Falling back to embedded policies: %s", err)
log.Error("Falling back to embedded policies", log.Err(err))
}
} else {
log.Logger.Debug("Policies successfully loaded from disk")
log.Debug("Policies successfully loaded from disk")
disableEmbedded = true
}
configScannerOptions = misconf.ScannerOption{
Expand All @@ -617,18 +618,18 @@ func initScannerConfig(opts flag.Options, cacheClient cache.Cache) (ScannerConfi
// Do not load config file for secret scanning
if opts.Scanners.Enabled(types.SecretScanner) {
ver := canonicalVersion(opts.AppVersion)
log.Logger.Info("Secret scanning is enabled")
log.Logger.Info("If your scanning is slow, please try '--scanners vuln' to disable secret scanning")
log.Logger.Infof("Please see also https://aquasecurity.github.io/trivy/%s/docs/scanner/secret/#recommendation for faster secret detection", ver)
log.Info("Secret scanning is enabled")
log.Info("If your scanning is slow, please try '--scanners vuln' to disable secret scanning")
log.Infof("Please see also https://aquasecurity.github.io/trivy/%s/docs/scanner/secret/#recommendation for faster secret detection", ver)
} else {
opts.SecretConfigPath = ""
}

if opts.Scanners.Enabled(types.LicenseScanner) {
if opts.LicenseFull {
log.Logger.Info("Full license scanning is enabled")
log.Info("Full license scanning is enabled")
} else {
log.Logger.Info("License scanning is enabled")
log.Info("License scanning is enabled")
}
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/commands/convert/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func Run(ctx context.Context, opts flag.Options) (err error) {
return xerrors.Errorf("unable to filter results: %w", err)
}

log.Logger.Debug("Writing report to output...")
log.Debug("Writing report to output...")
if err = report.Write(ctx, r, opts); err != nil {
return xerrors.Errorf("unable to write results: %w", err)
}
Expand Down
Loading

0 comments on commit 94d6e8c

Please sign in to comment.