Skip to content

Commit 94d6e8c

Browse files
knqyf263nikpivkinsimar7
authored
refactor: replace zap with slog (aquasecurity#6466)
Signed-off-by: knqyf263 <[email protected]> Co-authored-by: Nikita Pivkin <[email protected]> Co-authored-by: simar7 <[email protected]>
1 parent 336c47e commit 94d6e8c

File tree

164 files changed

+1657
-884
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

164 files changed

+1657
-884
lines changed

cmd/trivy/main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import (
1515

1616
func main() {
1717
if err := run(); err != nil {
18-
log.Fatal(err)
18+
log.Fatal("Fatal error", log.Err(err))
1919
}
2020
}
2121

magefiles/cloud_actions.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -206,10 +206,10 @@ func main() {
206206

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

215215
doc, err := htmlquery.LoadURL(serviceActionReferencesURL)

magefiles/docs.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,6 @@ func main() {
2424
cmd := commands.NewApp()
2525
cmd.DisableAutoGenTag = true
2626
if err := doc.GenMarkdownTree(cmd, "./docs/docs/references/configuration/cli"); err != nil {
27-
log.Fatal(err)
27+
log.Fatal("Fatal error", log.Err(err))
2828
}
2929
}

pkg/attestation/sbom/rekor.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ func (r *Rekor) RetrieveSBOM(ctx context.Context, digest string) ([]byte, error)
3939
return nil, ErrNoSBOMAttestation
4040
}
4141

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

4444
for _, ids := range lo.Chunk[rekor.EntryID](entryIDs, rekor.MaxGetEntriesLimit) {
4545
entries, err := r.client.GetEntries(ctx, ids)

pkg/attestation/sbom/rekor_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ func TestRekor_RetrieveSBOM(t *testing.T) {
3131
},
3232
}
3333

34-
require.NoError(t, log.InitLogger(false, true))
34+
log.InitLogger(false, true)
3535
for _, tt := range tests {
3636
t.Run(tt.name, func(t *testing.T) {
3737
ts := rekortest.NewServer(t)

pkg/cloud/aws/commands/run.go

+15-12
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import (
2323
var allSupportedServicesFunc = awsScanner.AllSupportedServices
2424

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

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

3333
svc := sts.NewFromConfig(cfg)
3434

35-
log.Logger.Debug("Looking up AWS caller identity...")
35+
log.DebugContext(ctx, "Looking up AWS caller identity...")
3636
result, err := svc.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{})
3737
if err != nil {
3838
return "", "", xerrors.Errorf("failed to discover AWS caller identity: %w", err)
3939
}
4040
if result.Account == nil {
4141
return "", "", xerrors.Errorf("missing account id for aws account")
4242
}
43-
log.Logger.Debugf("Verified AWS credentials for account %s!", *result.Account)
43+
log.DebugContext(ctx, "Verified AWS credentials for account!", log.String("account", *result.Account))
4444
return *result.Account, cfg.Region, nil
4545
}
4646

@@ -85,22 +85,22 @@ func processOptions(ctx context.Context, opt *flag.Options) error {
8585
}
8686
}
8787

88-
err := filterServices(opt)
88+
err := filterServices(ctx, opt)
8989
if err != nil {
9090
return err
9191
}
9292

93-
log.Logger.Debug("scanning services: ", opt.Services)
93+
log.DebugContext(ctx, "Scanning services", log.Any("services", opt.Services))
9494
return nil
9595
}
9696

97-
func filterServices(opt *flag.Options) error {
97+
func filterServices(ctx context.Context, opt *flag.Options) error {
9898
switch {
9999
case len(opt.Services) == 0 && len(opt.SkipServices) == 0:
100-
log.Logger.Debug("No service(s) specified, scanning all services...")
100+
log.DebugContext(ctx, "No service(s) specified, scanning all services...")
101101
opt.Services = allSupportedServicesFunc()
102102
case len(opt.SkipServices) > 0:
103-
log.Logger.Debug("excluding services: ", opt.SkipServices)
103+
log.DebugContext(ctx, "Excluding services", log.Any("services", opt.SkipServices))
104104
for _, s := range allSupportedServicesFunc() {
105105
if slices.Contains(opt.SkipServices, s) {
106106
continue
@@ -110,7 +110,8 @@ func filterServices(opt *flag.Options) error {
110110
}
111111
}
112112
case len(opt.Services) > 0:
113-
log.Logger.Debugf("Specific services were requested: [%s]...", strings.Join(opt.Services, ", "))
113+
log.DebugContext(ctx, "Specific services were requested...",
114+
log.String("services", strings.Join(opt.Services, ", ")))
114115
for _, service := range opt.Services {
115116
var found bool
116117
supported := allSupportedServicesFunc()
@@ -132,10 +133,12 @@ func Run(ctx context.Context, opt flag.Options) error {
132133
ctx, cancel := context.WithTimeout(ctx, opt.GlobalOptions.Timeout)
133134
defer cancel()
134135

136+
ctx = log.WithContextPrefix(ctx, "aws")
137+
135138
var err error
136139
defer func() {
137140
if errors.Is(err, context.DeadlineExceeded) {
138-
log.Logger.Warn("Increase --timeout value")
141+
log.Warn("Increase --timeout value")
139142
}
140143
}()
141144

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

158-
log.Logger.Debug("Writing report to output...")
161+
log.DebugContext(ctx, "Writing report to output...")
159162

160163
res := results.GetFailed()
161164
if opt.MisconfOptions.IncludeNonFailures {

pkg/cloud/aws/scanner/scanner.go

+8-5
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,21 @@ import (
2020
)
2121

2222
type AWSScanner struct {
23+
logger *log.Logger
2324
}
2425

2526
func NewScanner() *AWSScanner {
26-
return &AWSScanner{}
27+
return &AWSScanner{
28+
logger: log.WithPrefix("aws"),
29+
}
2730
}
2831

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

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

34-
prefixedLogger := &log.PrefixedLogger{Name: "aws"}
37+
prefixedLogger := log.NewWriteLogger(log.WithPrefix("aws"))
3538

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

9699
dataFS, dataPaths, err := misconf.CreateDataFS(option.RegoOptions.DataPaths)
97100
if err != nil {
98-
log.Logger.Errorf("Could not load config data: %s", err)
101+
s.logger.Error("Could not load config data", err)
99102
}
100103
scannerOpts = append(scannerOpts,
101104
options.ScannerWithDataDirs(dataPaths...),

pkg/commands/app.go

+7-9
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ func loadPluginCommands() []*cobra.Command {
114114
var commands []*cobra.Command
115115
plugins, err := plugin.LoadAll()
116116
if err != nil {
117-
log.Logger.Debugf("no plugins were loaded")
117+
log.Debug("No plugins loaded")
118118
return nil
119119
}
120120
for _, p := range plugins {
@@ -142,12 +142,12 @@ func initConfig(configFile string) error {
142142
viper.SetConfigType("yaml")
143143
if err := viper.ReadInConfig(); err != nil {
144144
if errors.Is(err, os.ErrNotExist) {
145-
log.Logger.Debugf("config file %q not found", configFile)
145+
log.Debug("Config file not found", log.String("file_path", configFile))
146146
return nil
147147
}
148148
return xerrors.Errorf("config file %q loading error: %s", configFile, err)
149149
}
150-
log.Logger.Infof("Loaded %s", configFile)
150+
log.Info("Loaded", log.String("file_path", configFile))
151151
return nil
152152
}
153153

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

198198
// Initialize logger
199-
if err := log.InitLogger(globalOptions.Debug, globalOptions.Quiet); err != nil {
200-
return err
201-
}
199+
log.InitLogger(globalOptions.Debug, globalOptions.Quiet)
202200

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

575573
if err := clientFlags.Bind(cmd); err != nil {
576574
return xerrors.Errorf("flag bind error: %w", err)
@@ -1040,7 +1038,7 @@ The following services are supported:
10401038
}
10411039
if opts.Timeout < time.Hour {
10421040
opts.Timeout = time.Hour
1043-
log.Logger.Debug("Timeout is set to less than 1 hour - upgrading to 1 hour for this command.")
1041+
log.Info("Timeout is set to less than 1 hour - upgrading to 1 hour for this command.")
10441042
}
10451043
return awscommands.Run(cmd.Context(), opts)
10461044
},
@@ -1106,7 +1104,7 @@ func NewVMCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command {
11061104
}
11071105
if options.Timeout < time.Minute*30 {
11081106
options.Timeout = time.Minute * 30
1109-
log.Logger.Debug("Timeout is set to less than 30 min - upgrading to 30 min for this command.")
1107+
log.Info("Timeout is set to less than 30 min - upgrading to 30 min for this command.")
11101108
}
11111109
return artifact.Run(cmd.Context(), options, artifact.TargetVM)
11121110
},

pkg/commands/artifact/run.go

+17-16
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ func (r *runner) initCache(opts flag.Options) error {
360360
if err != nil {
361361
return xerrors.Errorf("unable to initialize the cache: %w", err)
362362
}
363-
log.Logger.Debugf("cache dir: %s", fsutils.CacheDir())
363+
log.Debug("Cache dir", log.String("dir", fsutils.CacheDir()))
364364

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

401401
defer func() {
402402
if errors.Is(err, context.DeadlineExceeded) {
403-
log.Logger.Warn("Increase --timeout value")
403+
log.Warn("Increase --timeout value")
404404
}
405405
}()
406406

407407
if opts.GenerateDefaultConfig {
408-
log.Logger.Info("Writing the default config to trivy-default.yaml...")
408+
log.Info("Writing the default config to trivy-default.yaml...")
409409
return viper.SafeWriteConfigAs("trivy-default.yaml")
410410
}
411411

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

531-
log.Logger.Debugf("Enabling misconfiguration scanners: %s", included)
532+
log.Debug("Enabling misconfiguration scanners", log.Any("scanners", included))
532533
return lo.Without(all, included...), nil
533534
}
534535

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

571572
if len(opts.ImageConfigScanners) != 0 {
572-
log.Logger.Infof("Container image config scanners: %q", opts.ImageConfigScanners)
573+
log.Info("Container image config scanners", log.Any("scanners", opts.ImageConfigScanners))
573574
}
574575

575576
if opts.Scanners.Enabled(types.VulnerabilityScanner) {
576-
log.Logger.Info("Vulnerability scanning is enabled")
577-
log.Logger.Debugf("Vulnerability type: %s", scanOptions.VulnType)
577+
log.Info("Vulnerability scanning is enabled")
578+
log.Debug("Vulnerability type", log.Any("type", scanOptions.VulnType))
578579
}
579580

580581
// ScannerOption is filled only when config scanning is enabled.
581582
var configScannerOptions misconf.ScannerOption
582583
if opts.Scanners.Enabled(types.MisconfigScanner) || opts.ImageConfigScanners.Enabled(types.MisconfigScanner) {
583-
log.Logger.Info("Misconfiguration scanning is enabled")
584+
log.Info("Misconfiguration scanning is enabled")
584585

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

627628
if opts.Scanners.Enabled(types.LicenseScanner) {
628629
if opts.LicenseFull {
629-
log.Logger.Info("Full license scanning is enabled")
630+
log.Info("Full license scanning is enabled")
630631
} else {
631-
log.Logger.Info("License scanning is enabled")
632+
log.Info("License scanning is enabled")
632633
}
633634
}
634635

pkg/commands/convert/run.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ func Run(ctx context.Context, opts flag.Options) (err error) {
3939
return xerrors.Errorf("unable to filter results: %w", err)
4040
}
4141

42-
log.Logger.Debug("Writing report to output...")
42+
log.Debug("Writing report to output...")
4343
if err = report.Write(ctx, r, opts); err != nil {
4444
return xerrors.Errorf("unable to write results: %w", err)
4545
}

0 commit comments

Comments
 (0)