Skip to content

Commit 4b83798

Browse files
committed
Use global slog logger instead of log
Signed-off-by: Richard Wall <[email protected]>
1 parent 23579e7 commit 4b83798

File tree

6 files changed

+63
-71
lines changed

6 files changed

+63
-71
lines changed

pkg/agent/config.go

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ package agent
33
import (
44
"fmt"
55
"io"
6-
"log"
76
"net/url"
87
"os"
98
"time"
109

10+
"github.com/go-logr/logr"
1111
"github.com/hashicorp/go-multierror"
1212
"github.com/pkg/errors"
1313
"github.com/spf13/cobra"
@@ -355,7 +355,8 @@ type CombinedConfig struct {
355355
// The error returned may be a multierror.Error. Use multierror.Prefix(err,
356356
// "context:") rather than fmt.Errorf("context: %w", err) when wrapping the
357357
// error.
358-
func ValidateAndCombineConfig(log *log.Logger, cfg Config, flags AgentCmdFlags) (CombinedConfig, client.Client, error) {
358+
func ValidateAndCombineConfig(log logr.Logger, cfg Config, flags AgentCmdFlags) (CombinedConfig, client.Client, error) {
359+
359360
res := CombinedConfig{}
360361
var errs error
361362

@@ -364,23 +365,23 @@ func ValidateAndCombineConfig(log *log.Logger, cfg Config, flags AgentCmdFlags)
364365
switch {
365366
case flags.VenafiCloudMode && flags.CredentialsPath != "":
366367
mode = VenafiCloudKeypair
367-
log.Printf("Using the %s auth mode since --venafi-cloud and --credentials-path were specified.", mode)
368+
log.Info(fmt.Sprintf("Using the %s auth mode since --venafi-cloud and --credentials-path were specified.", mode))
368369
case flags.ClientID != "" && flags.PrivateKeyPath != "":
369370
mode = VenafiCloudKeypair
370-
log.Printf("Using the %s auth mode since --client-id and --private-key-path were specified.", mode)
371+
log.Info(fmt.Sprintf("Using the %s auth mode since --client-id and --private-key-path were specified.", mode))
371372
case flags.ClientID != "":
372373
return CombinedConfig{}, nil, fmt.Errorf("if --client-id is specified, --private-key-path must also be specified")
373374
case flags.PrivateKeyPath != "":
374375
return CombinedConfig{}, nil, fmt.Errorf("--private-key-path is specified, --client-id must also be specified")
375376
case flags.VenConnName != "":
376377
mode = VenafiCloudVenafiConnection
377-
log.Printf("Using the %s auth mode since --venafi-connection was specified.", mode)
378+
log.Info(fmt.Sprintf("Using the %s auth mode since --venafi-connection was specified.", mode))
378379
case flags.APIToken != "":
379380
mode = JetstackSecureAPIToken
380-
log.Printf("Using the %s auth mode since --api-token was specified.", mode)
381+
log.Info(fmt.Sprintf("Using the %s auth mode since --api-token was specified.", mode))
381382
case !flags.VenafiCloudMode && flags.CredentialsPath != "":
382383
mode = JetstackSecureOAuth
383-
log.Printf("Using the %s auth mode since --credentials-file was specified without --venafi-cloud.", mode)
384+
log.Info(fmt.Sprintf("Using the %s auth mode since --credentials-file was specified without --venafi-cloud.", mode))
384385
default:
385386
return CombinedConfig{}, nil, fmt.Errorf("no auth mode specified. You can use one of four auth modes:\n" +
386387
" - Use (--venafi-cloud with --credentials-file) or (--client-id with --private-key-path) to use the " + string(VenafiCloudKeypair) + " mode.\n" +
@@ -403,10 +404,10 @@ func ValidateAndCombineConfig(log *log.Logger, cfg Config, flags AgentCmdFlags)
403404
case hasServerField && hasEndpointField:
404405
// The `server` field takes precedence over the deprecated
405406
// `endpoint` field.
406-
log.Printf("The `server` and `endpoint` fields are both set in the config; using the `server` field.")
407+
log.Info("The `server` and `endpoint` fields are both set in the config; using the `server` field.")
407408
server = cfg.Server
408409
case !hasServerField && hasEndpointField:
409-
log.Printf("Using deprecated Endpoint configuration. User Server instead.")
410+
log.Info("Using deprecated Endpoint configuration. User Server instead.")
410411
if cfg.Endpoint.Protocol == "" && cfg.Server == "" {
411412
cfg.Endpoint.Protocol = "http"
412413
}
@@ -424,7 +425,7 @@ func ValidateAndCombineConfig(log *log.Logger, cfg Config, flags AgentCmdFlags)
424425
errs = multierror.Append(errs, fmt.Errorf("server %q is not a valid URL", server))
425426
}
426427
if res.AuthMode == VenafiCloudVenafiConnection && server != "" {
427-
log.Printf("ignoring the server field specified in the config file. In %s mode, this field is not needed.", VenafiCloudVenafiConnection)
428+
log.Info(fmt.Sprintf("Ignoring the server field specified in the config file. In %s mode, this field is not needed.", VenafiCloudVenafiConnection))
428429
server = ""
429430
}
430431
res.Server = server
@@ -454,7 +455,7 @@ func ValidateAndCombineConfig(log *log.Logger, cfg Config, flags AgentCmdFlags)
454455
// change this value with the new --venafi-connection flag, and this
455456
// field is simply ignored.
456457
if cfg.VenafiCloud != nil && cfg.VenafiCloud.UploadPath != "" {
457-
log.Printf(`ignoring the venafi-cloud.upload_path field in the config file. In %s mode, this field is not needed.`, res.AuthMode)
458+
log.Info(fmt.Sprintf(`Ignoring the venafi-cloud.upload_path field in the config file. In %s mode, this field is not needed.`, res.AuthMode))
458459
}
459460
uploadPath = ""
460461
}
@@ -472,7 +473,7 @@ func ValidateAndCombineConfig(log *log.Logger, cfg Config, flags AgentCmdFlags)
472473
// https://venafi.atlassian.net/browse/VC-35385 is done.
473474
{
474475
if cfg.VenafiCloud != nil && cfg.VenafiCloud.UploaderID != "" {
475-
log.Printf(`ignoring the venafi-cloud.uploader_id field in the config file. This field is not needed in %s mode.`, res.AuthMode)
476+
log.Info(fmt.Sprintf(`Ignoring the venafi-cloud.uploader_id field in the config file. This field is not needed in %s mode.`, res.AuthMode))
476477
}
477478
}
478479

@@ -524,13 +525,13 @@ func ValidateAndCombineConfig(log *log.Logger, cfg Config, flags AgentCmdFlags)
524525
case flags.Period == 0 && cfg.Period == 0:
525526
errs = multierror.Append(errs, fmt.Errorf("period must be set using --period or -p, or using the 'period' field in the config file"))
526527
case flags.Period == 0 && cfg.Period > 0:
527-
log.Printf("Using period from config %s", cfg.Period)
528+
log.Info("Using period from config", "period", cfg.Period)
528529
period = cfg.Period
529530
case flags.Period > 0 && cfg.Period == 0:
530531
period = flags.Period
531532
case flags.Period > 0 && cfg.Period > 0:
532533
// The flag takes precedence.
533-
log.Printf("Both the 'period' field and --period are set. Using the value provided with --period.")
534+
log.Info("Both the 'period' field and --period are set. Using the value provided with --period.")
534535
period = flags.Period
535536
}
536537
res.Period = period
@@ -599,7 +600,7 @@ func ValidateAndCombineConfig(log *log.Logger, cfg Config, flags AgentCmdFlags)
599600
// The error returned may be a multierror.Error. Use multierror.Prefix(err,
600601
// "context:") rather than fmt.Errorf("context: %w", err) when wrapping the
601602
// error.
602-
func validateCredsAndCreateClient(log *log.Logger, flagCredentialsPath, flagClientID, flagPrivateKeyPath, flagAPIToken string, cfg CombinedConfig) (client.Client, error) {
603+
func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClientID, flagPrivateKeyPath, flagAPIToken string, cfg CombinedConfig) (client.Client, error) {
603604
var errs error
604605

605606
var preflightClient client.Client
@@ -719,7 +720,7 @@ func ValidateDataGatherers(dataGatherers []DataGatherer) error {
719720

720721
// The error returned may be a multierror.Error. Instead of adding context to
721722
// the error with fmt.Errorf("%w", err), use multierror.Prefix(err, "context").
722-
func createCredentialClient(log *log.Logger, credentials client.Credentials, cfg CombinedConfig, agentMetadata *api.AgentMetadata) (client.Client, error) {
723+
func createCredentialClient(log logr.Logger, credentials client.Credentials, cfg CombinedConfig, agentMetadata *api.AgentMetadata) (client.Client, error) {
723724
switch creds := credentials.(type) {
724725
case *client.VenafiSvcAccountCredentials:
725726
// The uploader ID isn't actually used in the backend, let's use an
@@ -730,7 +731,7 @@ func createCredentialClient(log *log.Logger, credentials client.Credentials, cfg
730731
if cfg.AuthMode == VenafiCloudKeypair {
731732
// We don't do this for the VenafiCloudVenafiConnection mode because
732733
// the upload_path field is ignored in that mode.
733-
log.Println("Loading upload_path from \"venafi-cloud\" configuration.")
734+
log.Info("Loading upload_path from \"venafi-cloud\" configuration.")
734735
uploadPath = cfg.UploadPath
735736
}
736737
return client.NewVenafiCloudClient(agentMetadata, creds, cfg.Server, uploaderID, uploadPath, cfg.DisableCompression)

pkg/agent/config_test.go

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,16 @@ import (
66
"context"
77
"fmt"
88
"io"
9-
"log"
109
"net/http"
1110
"os"
1211
"testing"
1312
"time"
1413

14+
"github.com/go-logr/logr"
1515
"github.com/spf13/cobra"
1616
"github.com/stretchr/testify/assert"
1717
"github.com/stretchr/testify/require"
18+
"k8s.io/klog/v2/ktesting"
1819

1920
"github.com/jetstack/preflight/pkg/client"
2021
"github.com/jetstack/preflight/pkg/testutil"
@@ -86,7 +87,7 @@ func Test_ValidateAndCombineConfig(t *testing.T) {
8687

8788
t.Run("--period flag takes precedence over period field in config, shows warning", func(t *testing.T) {
8889
t.Setenv("POD_NAMESPACE", "venafi")
89-
log, gotLogs := recordLogs()
90+
log, gotLogs := recordLogs(t)
9091
got, _, err := ValidateAndCombineConfig(log,
9192
withConfig(testutil.Undent(`
9293
server: https://api.venafi.eu
@@ -97,8 +98,8 @@ func Test_ValidateAndCombineConfig(t *testing.T) {
9798
withCmdLineFlags("--period", "99m", "--credentials-file", fakeCredsPath))
9899
require.NoError(t, err)
99100
assert.Equal(t, testutil.Undent(`
100-
Using the Jetstack Secure OAuth auth mode since --credentials-file was specified without --venafi-cloud.
101-
Both the 'period' field and --period are set. Using the value provided with --period.
101+
INFO Using the Jetstack Secure OAuth auth mode since --credentials-file was specified without --venafi-cloud.
102+
INFO Both the 'period' field and --period are set. Using the value provided with --period.
102103
`), gotLogs.String())
103104
assert.Equal(t, 99*time.Minute, got.Period)
104105
})
@@ -573,7 +574,7 @@ func Test_ValidateAndCombineConfig(t *testing.T) {
573574
t.Run("venafi-cloud-workload-identity-auth: warning about server, venafi-cloud.uploader_id, and venafi-cloud.upload_path being skipped", func(t *testing.T) {
574575
t.Setenv("POD_NAMESPACE", "venafi")
575576
t.Setenv("KUBECONFIG", withFile(t, fakeKubeconfig))
576-
log, gotLogs := recordLogs()
577+
log, gotLogs := recordLogs(t)
577578
got, gotCl, err := ValidateAndCombineConfig(log,
578579
withConfig(testutil.Undent(`
579580
server: https://api.venafi.eu
@@ -587,11 +588,11 @@ func Test_ValidateAndCombineConfig(t *testing.T) {
587588
)
588589
require.NoError(t, err)
589590
assert.Equal(t, testutil.Undent(`
590-
Using the Venafi Cloud VenafiConnection auth mode since --venafi-connection was specified.
591-
ignoring the server field specified in the config file. In Venafi Cloud VenafiConnection mode, this field is not needed.
592-
ignoring the venafi-cloud.upload_path field in the config file. In Venafi Cloud VenafiConnection mode, this field is not needed.
593-
ignoring the venafi-cloud.uploader_id field in the config file. This field is not needed in Venafi Cloud VenafiConnection mode.
594-
Using period from config 1h0m0s
591+
INFO Using the Venafi Cloud VenafiConnection auth mode since --venafi-connection was specified.
592+
INFO Ignoring the server field specified in the config file. In Venafi Cloud VenafiConnection mode, this field is not needed.
593+
INFO Ignoring the venafi-cloud.upload_path field in the config file. In Venafi Cloud VenafiConnection mode, this field is not needed.
594+
INFO Ignoring the venafi-cloud.uploader_id field in the config file. This field is not needed in Venafi Cloud VenafiConnection mode.
595+
INFO Using period from config period="1h0m0s"
595596
`), gotLogs.String())
596597
assert.Equal(t, VenafiCloudVenafiConnection, got.AuthMode)
597598
assert.IsType(t, &client.VenConnClient{}, gotCl)
@@ -994,13 +995,15 @@ func withFile(t testing.TB, content string) string {
994995
return f.Name()
995996
}
996997

997-
func recordLogs() (*log.Logger, *bytes.Buffer) {
998-
b := bytes.Buffer{}
999-
return log.New(&b, "", 0), &b
998+
func recordLogs(t *testing.T) (logr.Logger, ktesting.Buffer) {
999+
log := ktesting.NewLogger(t, ktesting.NewConfig(ktesting.BufferLogs(true)))
1000+
testingLogger, ok := log.GetSink().(ktesting.Underlier)
1001+
require.True(t, ok)
1002+
return log, testingLogger.GetBuffer()
10001003
}
10011004

1002-
func discardLogs() *log.Logger {
1003-
return log.New(io.Discard, "", 0)
1005+
func discardLogs() logr.Logger {
1006+
return logr.Discard()
10041007
}
10051008

10061009
// Shortcut for ParseConfig.

pkg/agent/run.go

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,14 @@ import (
77
"errors"
88
"fmt"
99
"io"
10+
"log/slog"
1011
"net/http"
1112
"os"
1213
"strings"
1314
"time"
1415

1516
"github.com/cenkalti/backoff"
17+
"github.com/go-logr/logr"
1618
"github.com/hashicorp/go-multierror"
1719
"github.com/prometheus/client_golang/prometheus"
1820
"github.com/prometheus/client_golang/prometheus/promhttp"
@@ -31,7 +33,6 @@ import (
3133
"github.com/jetstack/preflight/pkg/client"
3234
"github.com/jetstack/preflight/pkg/datagatherer"
3335
"github.com/jetstack/preflight/pkg/kubeconfig"
34-
"github.com/jetstack/preflight/pkg/logs"
3536
"github.com/jetstack/preflight/pkg/version"
3637

3738
"net/http/pprof"
@@ -49,7 +50,7 @@ const schemaVersion string = "v2.0.0"
4950

5051
// Run starts the agent process
5152
func Run(cmd *cobra.Command, args []string) error {
52-
logs.Log.Printf("Preflight agent version: %s (%s)", version.PreflightVersion, version.Commit)
53+
slog.Info("Starting agent", "version", version.PreflightVersion, "commit", version.Commit)
5354
ctx, cancel := context.WithCancel(context.Background())
5455
defer cancel()
5556

@@ -69,7 +70,7 @@ func Run(cmd *cobra.Command, args []string) error {
6970
return fmt.Errorf("Failed to parse config file: %s", err)
7071
}
7172

72-
config, preflightClient, err := ValidateAndCombineConfig(logs.Log, cfg, Flags)
73+
config, preflightClient, err := ValidateAndCombineConfig(logr.FromSlogHandler(slog.Default().Handler()), cfg, Flags)
7374
if err != nil {
7475
return fmt.Errorf("While evaluating configuration: %v", err)
7576
}
@@ -87,9 +88,9 @@ func Run(cmd *cobra.Command, args []string) error {
8788

8889
group.Go(func() error {
8990
server := http.NewServeMux()
90-
91+
log := slog.With("port", ":8081")
9192
if Flags.Profiling {
92-
logs.Log.Printf("pprof profiling was enabled.")
93+
log.Info("pprof enabled", "endpoint", "/debug/pprof")
9394
server.HandleFunc("/debug/pprof/", pprof.Index)
9495
server.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
9596
server.HandleFunc("/debug/pprof/profile", pprof.Profile)
@@ -98,7 +99,7 @@ func Run(cmd *cobra.Command, args []string) error {
9899
}
99100

100101
if Flags.Prometheus {
101-
logs.Log.Printf("Prometheus was enabled.\nRunning prometheus on port :8081")
102+
log.Info("metrics enabled", "endpoint", "/metrics")
102103
prometheus.MustRegister(metricPayloadSize)
103104
server.Handle("/metrics", promhttp.Handler())
104105
}
@@ -159,7 +160,7 @@ func Run(cmd *cobra.Command, args []string) error {
159160
return fmt.Errorf("failed to instantiate %q data gatherer %q: %v", kind, dgConfig.Name, err)
160161
}
161162

162-
logs.Log.Printf("starting %q datagatherer", dgConfig.Name)
163+
slog.Info("Starting datagatherer", "gatherer", dgConfig.Name)
163164

164165
// start the data gatherers and wait for the cache sync
165166
group.Go(func() error {
@@ -194,7 +195,7 @@ func Run(cmd *cobra.Command, args []string) error {
194195
// the run.
195196
if err := dg.WaitForCacheSync(bootCtx.Done()); err != nil {
196197
// log sync failure, this might recover in future
197-
logs.Log.Printf("failed to complete initial sync of %q data gatherer %q: %v", dgConfig.Kind, dgConfig.Name, err)
198+
slog.Warn("Failed to complete initial sync", "kind", dgConfig.Kind, "gatherer", dgConfig.Name, "reason", err)
198199
}
199200
}
200201

@@ -237,7 +238,7 @@ func newEventf(installNS string) (Eventf, error) {
237238
var eventf Eventf
238239
if os.Getenv("POD_NAME") == "" {
239240
eventf = func(eventType, reason, msg string, args ...interface{}) {}
240-
logs.Log.Printf("error messages will not show in the pod's events because the POD_NAME environment variable is empty")
241+
slog.Warn("Error messages will not show in the pod's events because the POD_NAME environment variable is empty")
241242
} else {
242243
podName := os.Getenv("POD_NAME")
243244

@@ -263,7 +264,7 @@ func gatherAndOutputData(eventf Eventf, config CombinedConfig, preflightClient c
263264
var readings []*api.DataReading
264265

265266
if config.InputPath != "" {
266-
logs.Log.Printf("Reading data from local file: %s", config.InputPath)
267+
slog.Info("Reading data from local file", "path", config.InputPath)
267268
data, err := os.ReadFile(config.InputPath)
268269
if err != nil {
269270
return fmt.Errorf("failed to read local data file: %s", err)
@@ -289,7 +290,7 @@ func gatherAndOutputData(eventf Eventf, config CombinedConfig, preflightClient c
289290
if err != nil {
290291
return fmt.Errorf("failed to output to local file: %s", err)
291292
}
292-
logs.Log.Printf("Data saved to local file: %s", config.OutputPath)
293+
slog.Info("Data saved to local file", "path", config.OutputPath)
293294
} else {
294295
backOff := backoff.NewExponentialBackOff()
295296
backOff.InitialInterval = 30 * time.Second
@@ -300,7 +301,7 @@ func gatherAndOutputData(eventf Eventf, config CombinedConfig, preflightClient c
300301
}
301302
err := backoff.RetryNotify(post, backOff, func(err error, t time.Duration) {
302303
eventf("Warning", "PushingErr", "retrying in %v after error: %s", t, err)
303-
logs.Log.Printf("retrying in %v after error: %s", t, err)
304+
slog.Warn("Pushing error", "backoffInterval", t, "reason", err)
304305
})
305306
if err != nil {
306307
return fmt.Errorf("Exiting due to fatal error uploading: %v", err)
@@ -321,11 +322,8 @@ func gatherData(config CombinedConfig, dataGatherers map[string]datagatherer.Dat
321322
continue
322323
}
323324

324-
if count >= 0 {
325-
logs.Log.Printf("successfully gathered %d items from %q datagatherer", count, k)
326-
} else {
327-
logs.Log.Printf("successfully gathered data from %q datagatherer", k)
328-
}
325+
slog.Info("Successfully gathered data", "gatherer", k, "count", count)
326+
329327
readings = append(readings, &api.DataReading{
330328
ClusterID: config.ClusterID,
331329
DataGatherer: k,
@@ -357,7 +355,7 @@ func gatherData(config CombinedConfig, dataGatherers map[string]datagatherer.Dat
357355
func postData(config CombinedConfig, preflightClient client.Client, readings []*api.DataReading) error {
358356
baseURL := config.Server
359357

360-
logs.Log.Println("Posting data to:", baseURL)
358+
slog.Info("Posting data", "to", baseURL)
361359

362360
if config.AuthMode == VenafiCloudKeypair || config.AuthMode == VenafiCloudVenafiConnection {
363361
// orgID and clusterID are not required for Venafi Cloud auth
@@ -368,7 +366,7 @@ func postData(config CombinedConfig, preflightClient client.Client, readings []*
368366
if err != nil {
369367
return fmt.Errorf("post to server failed: %+v", err)
370368
}
371-
logs.Log.Println("Data sent successfully.")
369+
slog.Info("Data sent successfully")
372370

373371
return nil
374372
}
@@ -384,7 +382,7 @@ func postData(config CombinedConfig, preflightClient client.Client, readings []*
384382
prometheus.Labels{"organization": config.OrganizationID, "cluster": config.ClusterID},
385383
)
386384
metric.Set(float64(len(data)))
387-
logs.Log.Printf("Data readings upload size: %d", len(data))
385+
slog.Info("Data readings", "uploadSize", len(data))
388386
path := config.EndpointPath
389387
if path == "" {
390388
path = "/api/v1/datareadings"
@@ -404,7 +402,7 @@ func postData(config CombinedConfig, preflightClient client.Client, readings []*
404402

405403
return fmt.Errorf("received response with status code %d. Body: [%s]", code, errorContent)
406404
}
407-
logs.Log.Println("Data sent successfully.")
405+
slog.Info("Data sent successfully")
408406
return err
409407
}
410408

@@ -416,7 +414,7 @@ func postData(config CombinedConfig, preflightClient client.Client, readings []*
416414
if err != nil {
417415
return fmt.Errorf("post to server failed: %+v", err)
418416
}
419-
logs.Log.Println("Data sent successfully.")
417+
slog.Info("Data sent successfully")
420418

421419
return nil
422420
}

0 commit comments

Comments
 (0)