diff --git a/go.mod b/go.mod index 1e01bd88ab..4248e13158 100644 --- a/go.mod +++ b/go.mod @@ -27,7 +27,7 @@ require ( github.com/containernetworking/plugins v0.9.1 github.com/coreos/go-iptables v0.6.0 github.com/coreos/go-semver v0.3.0 - github.com/cosi-project/runtime v0.0.0-20210409233936-10d6103c19ab + github.com/cosi-project/runtime v0.0.0-20210521140557-8a4533ce68e2 github.com/docker/distribution v2.7.1+incompatible github.com/docker/docker v20.10.6+incompatible github.com/docker/go-connections v0.4.0 @@ -85,6 +85,7 @@ require ( go.etcd.io/etcd/client/pkg/v3 v3.5.0-beta.3 go.etcd.io/etcd/client/v3 v3.5.0-beta.3 go.etcd.io/etcd/etcdutl/v3 v3.5.0-beta.3 + go.uber.org/zap v1.16.1-0.20210329175301-c23abee72d19 golang.org/x/net v0.0.0-20210505214959-0714010a04ed golang.org/x/sync v0.0.0-20210220032951-036812b2e83c golang.org/x/sys v0.0.0-20210503173754-0981d6026fa6 diff --git a/go.sum b/go.sum index 7bb90756ad..09ca9ecd29 100644 --- a/go.sum +++ b/go.sum @@ -324,8 +324,9 @@ github.com/coreos/go-systemd/v22 v22.3.1 h1:7OO2CXWMYNDdaAzP51t4lCCZWwpQHmvPbm9s github.com/coreos/go-systemd/v22 v22.3.1/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/cosi-project/runtime v0.0.0-20210409233936-10d6103c19ab h1:u8p7SXdsdYV89RnXtPExlvIKDrXLeGhAUo66LmOtYV4= github.com/cosi-project/runtime v0.0.0-20210409233936-10d6103c19ab/go.mod h1:ebaL1B5YO0vy0YuhHS59QrRfZEYPNB9U3bzdLrlUfzo= +github.com/cosi-project/runtime v0.0.0-20210521140557-8a4533ce68e2 h1:+dYE69Cq6tZMs+qWoiSUU/i8tHzSRJesl+4qBzcBXJg= +github.com/cosi-project/runtime v0.0.0-20210521140557-8a4533ce68e2/go.mod h1:v/3MIWNuuOSdXXMl3QgCSwZrAk1fTOmQHEnTAfvDqP4= github.com/cpuguy83/go-md2man v1.0.10 h1:BSKMNlYxDvnunlTymqtgONjNnaRV1sTpcovwwjF22jk= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= @@ -1357,17 +1358,20 @@ go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5/go.mod h1:nmDLcffg48OtT/PSW0H go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/goleak v1.1.10 h1:z+mqJhf6ss6BSfSM671tgKyZBFPTTJM+HLxnhPC3wu0= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= +go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= go.uber.org/zap v1.16.1-0.20210329175301-c23abee72d19 h1:040c3dLNhgFQkoojH2AMpHCy4SrvhmxdU72d9GLGGE0= go.uber.org/zap v1.16.1-0.20210329175301-c23abee72d19/go.mod h1:aMfIlz3TDBfB0BwTCKFU1XbEmj9zevr5S5LcBr85MXw= go4.org/intern v0.0.0-20210108033219-3eb7198706b2 h1:VFTf+jjIgsldaz/Mr00VaCSswHJrI2hIjQygE/W4IMg= diff --git a/internal/app/machined/pkg/controllers/config/k8s_control_plane.go b/internal/app/machined/pkg/controllers/config/k8s_control_plane.go index 339c9dd8df..cbf64dd008 100644 --- a/internal/app/machined/pkg/controllers/config/k8s_control_plane.go +++ b/internal/app/machined/pkg/controllers/config/k8s_control_plane.go @@ -7,7 +7,6 @@ package config import ( "context" "fmt" - "log" "strings" "github.com/AlekSi/pointer" @@ -15,6 +14,7 @@ import ( "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" talosnet "github.com/talos-systems/net" + "go.uber.org/zap" "github.com/talos-systems/talos/pkg/images" talosconfig "github.com/talos-systems/talos/pkg/machinery/config" @@ -62,7 +62,7 @@ func (ctrl *K8sControlPlaneController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint:gocyclo -func (ctrl *K8sControlPlaneController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *K8sControlPlaneController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { for { select { case <-ctx.Done(): @@ -104,7 +104,7 @@ func (ctrl *K8sControlPlaneController) Run(ctx context.Context, r controller.Run continue } - for _, f := range []func(context.Context, controller.Runtime, *log.Logger, talosconfig.Provider) error{ + for _, f := range []func(context.Context, controller.Runtime, *zap.Logger, talosconfig.Provider) error{ ctrl.manageAPIServerConfig, ctrl.manageControllerManagerConfig, ctrl.manageSchedulerConfig, @@ -133,7 +133,7 @@ func convertVolumes(volumes []talosconfig.VolumeMount) []config.K8sExtraVolume { return result } -func (ctrl *K8sControlPlaneController) manageAPIServerConfig(ctx context.Context, r controller.Runtime, logger *log.Logger, cfgProvider talosconfig.Provider) error { +func (ctrl *K8sControlPlaneController) manageAPIServerConfig(ctx context.Context, r controller.Runtime, logger *zap.Logger, cfgProvider talosconfig.Provider) error { var cloudProvider string if cfgProvider.Cluster().ExternalCloudProvider().Enabled() { cloudProvider = "external" @@ -155,7 +155,7 @@ func (ctrl *K8sControlPlaneController) manageAPIServerConfig(ctx context.Context }) } -func (ctrl *K8sControlPlaneController) manageControllerManagerConfig(ctx context.Context, r controller.Runtime, logger *log.Logger, cfgProvider talosconfig.Provider) error { +func (ctrl *K8sControlPlaneController) manageControllerManagerConfig(ctx context.Context, r controller.Runtime, logger *zap.Logger, cfgProvider talosconfig.Provider) error { var cloudProvider string if cfgProvider.Cluster().ExternalCloudProvider().Enabled() { cloudProvider = "external" @@ -175,7 +175,7 @@ func (ctrl *K8sControlPlaneController) manageControllerManagerConfig(ctx context }) } -func (ctrl *K8sControlPlaneController) manageSchedulerConfig(ctx context.Context, r controller.Runtime, logger *log.Logger, cfgProvider talosconfig.Provider) error { +func (ctrl *K8sControlPlaneController) manageSchedulerConfig(ctx context.Context, r controller.Runtime, logger *zap.Logger, cfgProvider talosconfig.Provider) error { return r.Modify(ctx, config.NewK8sControlPlaneScheduler(), func(r resource.Resource) error { r.(*config.K8sControlPlane).SetScheduler(config.K8sControlPlaneSchedulerSpec{ Image: cfgProvider.Cluster().Scheduler().Image(), @@ -187,7 +187,7 @@ func (ctrl *K8sControlPlaneController) manageSchedulerConfig(ctx context.Context }) } -func (ctrl *K8sControlPlaneController) manageManifestsConfig(ctx context.Context, r controller.Runtime, logger *log.Logger, cfgProvider talosconfig.Provider) error { +func (ctrl *K8sControlPlaneController) manageManifestsConfig(ctx context.Context, r controller.Runtime, logger *zap.Logger, cfgProvider talosconfig.Provider) error { dnsServiceIPs, err := cfgProvider.Cluster().Network().DNSServiceIPs() if err != nil { return fmt.Errorf("error calculating DNS service IPs: %w", err) @@ -239,7 +239,7 @@ func (ctrl *K8sControlPlaneController) manageManifestsConfig(ctx context.Context }) } -func (ctrl *K8sControlPlaneController) manageExtraManifestsConfig(ctx context.Context, r controller.Runtime, logger *log.Logger, cfgProvider talosconfig.Provider) error { +func (ctrl *K8sControlPlaneController) manageExtraManifestsConfig(ctx context.Context, r controller.Runtime, logger *zap.Logger, cfgProvider talosconfig.Provider) error { return r.Modify(ctx, config.NewK8sExtraManifests(), func(r resource.Resource) error { spec := config.K8sExtraManifestsSpec{} @@ -282,6 +282,6 @@ func (ctrl *K8sControlPlaneController) manageExtraManifestsConfig(ctx context.Co }) } -func (ctrl *K8sControlPlaneController) teardownAll(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *K8sControlPlaneController) teardownAll(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { return nil } diff --git a/internal/app/machined/pkg/controllers/config/k8s_control_plane_test.go b/internal/app/machined/pkg/controllers/config/k8s_control_plane_test.go index e9b471a47c..53eacc328e 100644 --- a/internal/app/machined/pkg/controllers/config/k8s_control_plane_test.go +++ b/internal/app/machined/pkg/controllers/config/k8s_control_plane_test.go @@ -24,6 +24,7 @@ import ( "github.com/talos-systems/go-retry/retry" configctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/config" + "github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine" "github.com/talos-systems/talos/pkg/resources/config" @@ -49,9 +50,7 @@ func (suite *K8sControlPlaneSuite) SetupTest() { var err error - logger := log.New(log.Writer(), "controller-runtime: ", log.Flags()) - - suite.runtime, err = runtime.NewRuntime(suite.state, logger) + suite.runtime, err = runtime.NewRuntime(suite.state, logging.Wrap(log.Writer())) suite.Require().NoError(err) suite.Require().NoError(suite.runtime.RegisterController(&configctrl.K8sControlPlaneController{})) diff --git a/internal/app/machined/pkg/controllers/config/machine_type.go b/internal/app/machined/pkg/controllers/config/machine_type.go index 11ee19eb43..af024fe26a 100644 --- a/internal/app/machined/pkg/controllers/config/machine_type.go +++ b/internal/app/machined/pkg/controllers/config/machine_type.go @@ -7,12 +7,12 @@ package config import ( "context" "fmt" - "log" "github.com/AlekSi/pointer" "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" + "go.uber.org/zap" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine" "github.com/talos-systems/talos/pkg/resources/config" @@ -49,7 +49,7 @@ func (ctrl *MachineTypeController) Outputs() []controller.Output { } // Run implements controller.Controller interface. -func (ctrl *MachineTypeController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *MachineTypeController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { for { select { case <-ctx.Done(): diff --git a/internal/app/machined/pkg/controllers/k8s/control_plane_static_pod.go b/internal/app/machined/pkg/controllers/k8s/control_plane_static_pod.go index 878538519b..d711a05d62 100644 --- a/internal/app/machined/pkg/controllers/k8s/control_plane_static_pod.go +++ b/internal/app/machined/pkg/controllers/k8s/control_plane_static_pod.go @@ -7,7 +7,6 @@ package k8s import ( "context" "fmt" - "log" "path/filepath" "strings" @@ -15,6 +14,7 @@ import ( "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" + "go.uber.org/zap" v1 "k8s.io/api/core/v1" apiresource "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -63,7 +63,7 @@ func (ctrl *ControlPlaneStaticPodController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint:gocyclo -func (ctrl *ControlPlaneStaticPodController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *ControlPlaneStaticPodController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { for { select { case <-ctx.Done(): @@ -87,7 +87,7 @@ func (ctrl *ControlPlaneStaticPodController) Run(ctx context.Context, r controll secretsVersion := secretsStatusResource.(*k8s.SecretsStatus).Status().Version for _, pod := range []struct { - f func(context.Context, controller.Runtime, *log.Logger, *config.K8sControlPlane, string) error + f func(context.Context, controller.Runtime, *zap.Logger, *config.K8sControlPlane, string) error id resource.ID }{ { @@ -167,7 +167,7 @@ func volumes(volumes []config.K8sExtraVolume) []v1.Volume { return result } -func (ctrl *ControlPlaneStaticPodController) manageAPIServer(ctx context.Context, r controller.Runtime, logger *log.Logger, configResource *config.K8sControlPlane, secretsVersion string) error { +func (ctrl *ControlPlaneStaticPodController) manageAPIServer(ctx context.Context, r controller.Runtime, logger *zap.Logger, configResource *config.K8sControlPlane, secretsVersion string) error { cfg := configResource.APIServer() args := []string{ @@ -293,7 +293,7 @@ func (ctrl *ControlPlaneStaticPodController) manageAPIServer(ctx context.Context } func (ctrl *ControlPlaneStaticPodController) manageControllerManager(ctx context.Context, r controller.Runtime, - logger *log.Logger, configResource *config.K8sControlPlane, secretsVersion string) error { + logger *zap.Logger, configResource *config.K8sControlPlane, secretsVersion string) error { cfg := configResource.ControllerManager() args := []string{ @@ -394,7 +394,7 @@ func (ctrl *ControlPlaneStaticPodController) manageControllerManager(ctx context } func (ctrl *ControlPlaneStaticPodController) manageScheduler(ctx context.Context, r controller.Runtime, - logger *log.Logger, configResource *config.K8sControlPlane, secretsVersion string) error { + logger *zap.Logger, configResource *config.K8sControlPlane, secretsVersion string) error { cfg := configResource.Scheduler() args := []string{ diff --git a/internal/app/machined/pkg/controllers/k8s/control_plane_static_pod_test.go b/internal/app/machined/pkg/controllers/k8s/control_plane_static_pod_test.go index e7edc1d4ad..9a80d82e2f 100644 --- a/internal/app/machined/pkg/controllers/k8s/control_plane_static_pod_test.go +++ b/internal/app/machined/pkg/controllers/k8s/control_plane_static_pod_test.go @@ -23,6 +23,7 @@ import ( v1 "k8s.io/api/core/v1" k8sctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/k8s" + "github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/resources/config" "github.com/talos-systems/talos/pkg/resources/k8s" @@ -47,9 +48,7 @@ func (suite *ControlPlaneStaticPodSuite) SetupTest() { var err error - logger := log.New(log.Writer(), "controller-runtime: ", log.Flags()) - - suite.runtime, err = runtime.NewRuntime(suite.state, logger) + suite.runtime, err = runtime.NewRuntime(suite.state, logging.Wrap(log.Writer())) suite.Require().NoError(err) suite.Require().NoError(suite.runtime.RegisterController(&k8sctrl.ControlPlaneStaticPodController{})) diff --git a/internal/app/machined/pkg/controllers/k8s/extra_manifest.go b/internal/app/machined/pkg/controllers/k8s/extra_manifest.go index 44841d6c8a..f5d6832cff 100644 --- a/internal/app/machined/pkg/controllers/k8s/extra_manifest.go +++ b/internal/app/machined/pkg/controllers/k8s/extra_manifest.go @@ -8,7 +8,6 @@ import ( "context" "fmt" "io/ioutil" - "log" "net/http" "os" "path/filepath" @@ -19,6 +18,7 @@ import ( "github.com/cosi-project/runtime/pkg/state" "github.com/hashicorp/go-getter" "github.com/hashicorp/go-multierror" + "go.uber.org/zap" "github.com/talos-systems/talos/pkg/resources/config" "github.com/talos-systems/talos/pkg/resources/k8s" @@ -64,7 +64,7 @@ func (ctrl *ExtraManifestController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint:gocyclo -func (ctrl *ExtraManifestController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *ExtraManifestController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { for { select { case <-ctx.Done(): @@ -139,7 +139,7 @@ func (ctrl *ExtraManifestController) Run(ctx context.Context, r controller.Runti } } -func (ctrl *ExtraManifestController) process(ctx context.Context, r controller.Runtime, logger *log.Logger, manifest config.ExtraManifest) (id resource.ID, err error) { +func (ctrl *ExtraManifestController) process(ctx context.Context, r controller.Runtime, logger *zap.Logger, manifest config.ExtraManifest) (id resource.ID, err error) { id = fmt.Sprintf("%s-%s", manifest.Priority, manifest.Name) // inline manifests don't require download @@ -150,7 +150,7 @@ func (ctrl *ExtraManifestController) process(ctx context.Context, r controller.R return id, ctrl.processURL(ctx, r, logger, manifest, id) } -func (ctrl *ExtraManifestController) processURL(ctx context.Context, r controller.Runtime, logger *log.Logger, manifest config.ExtraManifest, id resource.ID) (err error) { +func (ctrl *ExtraManifestController) processURL(ctx context.Context, r controller.Runtime, logger *zap.Logger, manifest config.ExtraManifest, id resource.ID) (err error) { var tmpDir string tmpDir, err = ioutil.TempDir("", "talos") @@ -195,7 +195,7 @@ func (ctrl *ExtraManifestController) processURL(ctx context.Context, r controlle return } - logger.Printf("downloaded manifest %q", manifest.URL) + logger.Sugar().Infof("downloaded manifest %q", manifest.URL) var contents []byte diff --git a/internal/app/machined/pkg/controllers/k8s/extra_manifest_test.go b/internal/app/machined/pkg/controllers/k8s/extra_manifest_test.go index d65f654a9d..1b742c3f0f 100644 --- a/internal/app/machined/pkg/controllers/k8s/extra_manifest_test.go +++ b/internal/app/machined/pkg/controllers/k8s/extra_manifest_test.go @@ -23,6 +23,7 @@ import ( "github.com/talos-systems/go-retry/retry" k8sctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/k8s" + "github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/resources/config" "github.com/talos-systems/talos/pkg/resources/k8s" "github.com/talos-systems/talos/pkg/resources/v1alpha1" @@ -47,9 +48,7 @@ func (suite *ExtraManifestSuite) SetupTest() { var err error - logger := log.New(log.Writer(), "controller-runtime: ", log.Flags()) - - suite.runtime, err = runtime.NewRuntime(suite.state, logger) + suite.runtime, err = runtime.NewRuntime(suite.state, logging.Wrap(log.Writer())) suite.Require().NoError(err) suite.Require().NoError(suite.runtime.RegisterController(&k8sctrl.ExtraManifestController{})) diff --git a/internal/app/machined/pkg/controllers/k8s/kubelet_static_pod_controller.go b/internal/app/machined/pkg/controllers/k8s/kubelet_static_pod_controller.go index 512dc79c3b..ca97391b1a 100644 --- a/internal/app/machined/pkg/controllers/k8s/kubelet_static_pod_controller.go +++ b/internal/app/machined/pkg/controllers/k8s/kubelet_static_pod_controller.go @@ -9,7 +9,6 @@ import ( "context" "fmt" "io/ioutil" - "log" "os" "path/filepath" "strings" @@ -19,6 +18,7 @@ import ( "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" + "go.uber.org/zap" "gopkg.in/yaml.v3" "github.com/talos-systems/talos/pkg/kubernetes/kubelet" @@ -84,7 +84,7 @@ func (ctrl *KubeletStaticPodController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint:gocyclo,cyclop -func (ctrl *KubeletStaticPodController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *KubeletStaticPodController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { var kubeletClient *kubelet.Client refreshTicker := time.NewTicker(15 * time.Second) // refresh kubelet pods status every 15 seconds @@ -170,7 +170,7 @@ func (ctrl *KubeletStaticPodController) Run(ctx context.Context, r controller.Ru } if bootstrapStatus.(*v1alpha1.BootstrapStatus).Status().SelfHostedControlPlane { - logger.Print("skipped as running self-hosted control plane") + logger.Info("skipped as running self-hosted control plane") if err = ctrl.cleanupPods(logger, nil); err != nil { return fmt.Errorf("error cleaning up static pods: %w", err) @@ -218,7 +218,7 @@ func (ctrl *KubeletStaticPodController) podFilename(staticPod resource.Resource) return fmt.Sprintf("%s%s.yaml", constants.TalosManifestPrefix, staticPod.Metadata().ID()) } -func (ctrl *KubeletStaticPodController) writePod(ctx context.Context, r controller.Runtime, logger *log.Logger, staticPod resource.Resource) error { +func (ctrl *KubeletStaticPodController) writePod(ctx context.Context, r controller.Runtime, logger *zap.Logger, staticPod resource.Resource) error { staticPodStatus := k8s.NewStaticPodStatus(staticPod.Metadata().Namespace(), staticPod.Metadata().ID()) if err := r.AddFinalizer(ctx, staticPod.Metadata(), staticPodStatus.String()); err != nil { @@ -243,12 +243,12 @@ func (ctrl *KubeletStaticPodController) writePod(ctx context.Context, r controll return nil } - logger.Printf("writing static pod %q", podPath) + logger.Sugar().Infof("writing static pod %q", podPath) return ioutil.WriteFile(podPath, renderedPod, 0o600) } -func (ctrl *KubeletStaticPodController) teardownPod(logger *log.Logger, staticPod resource.Resource) error { +func (ctrl *KubeletStaticPodController) teardownPod(logger *zap.Logger, staticPod resource.Resource) error { podPath := ctrl.podPath(staticPod) _, err := os.Stat(podPath) @@ -260,7 +260,7 @@ func (ctrl *KubeletStaticPodController) teardownPod(logger *log.Logger, staticPo return fmt.Errorf("error checking static pod status: %w", err) } - logger.Printf("removing static pod %q", podPath) + logger.Sugar().Infof("removing static pod %q", podPath) if err = os.Remove(podPath); err != nil { return fmt.Errorf("error removing static pod %q: %w", podPath, err) @@ -269,7 +269,7 @@ func (ctrl *KubeletStaticPodController) teardownPod(logger *log.Logger, staticPo return nil } -func (ctrl *KubeletStaticPodController) cleanupPods(logger *log.Logger, staticPods []resource.Resource) error { +func (ctrl *KubeletStaticPodController) cleanupPods(logger *zap.Logger, staticPods []resource.Resource) error { manifestDir, err := os.Open(constants.ManifestsDirectory) if err != nil { return fmt.Errorf("error opening manifests directory: %w", err) @@ -300,7 +300,7 @@ func (ctrl *KubeletStaticPodController) cleanupPods(logger *log.Logger, staticPo podPath := filepath.Join(constants.ManifestsDirectory, manifest) - logger.Printf("cleaning up static pod %q", podPath) + logger.Sugar().Infof("cleaning up static pod %q", podPath) if err = os.Remove(podPath); err != nil { return fmt.Errorf("error cleaning up static pod: %w", err) diff --git a/internal/app/machined/pkg/controllers/k8s/manifest.go b/internal/app/machined/pkg/controllers/k8s/manifest.go index 9db5777121..f25eae82e2 100644 --- a/internal/app/machined/pkg/controllers/k8s/manifest.go +++ b/internal/app/machined/pkg/controllers/k8s/manifest.go @@ -9,13 +9,13 @@ import ( "context" "encoding/json" "fmt" - "log" "text/template" "github.com/AlekSi/pointer" "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" + "go.uber.org/zap" "github.com/talos-systems/talos/pkg/resources/config" "github.com/talos-systems/talos/pkg/resources/k8s" @@ -61,7 +61,7 @@ func (ctrl *ManifestController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint:gocyclo -func (ctrl *ManifestController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *ManifestController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { for { select { case <-ctx.Done(): diff --git a/internal/app/machined/pkg/controllers/k8s/manifest_apply.go b/internal/app/machined/pkg/controllers/k8s/manifest_apply.go index 89bb3bad06..f441de740c 100644 --- a/internal/app/machined/pkg/controllers/k8s/manifest_apply.go +++ b/internal/app/machined/pkg/controllers/k8s/manifest_apply.go @@ -7,7 +7,6 @@ package k8s import ( "context" "fmt" - "log" "sort" "github.com/AlekSi/pointer" @@ -15,6 +14,8 @@ import ( "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" "go.etcd.io/etcd/client/v3/concurrency" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -29,6 +30,7 @@ import ( clientcmdapi "k8s.io/client-go/tools/clientcmd/api" "github.com/talos-systems/talos/internal/pkg/etcd" + "github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/resources/k8s" "github.com/talos-systems/talos/pkg/resources/secrets" @@ -79,7 +81,7 @@ func (ctrl *ManifestApplyController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint:gocyclo -func (ctrl *ManifestApplyController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *ManifestApplyController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { for { select { case <-ctx.Done(): @@ -108,7 +110,7 @@ func (ctrl *ManifestApplyController) Run(ctx context.Context, r controller.Runti } if bootstrapStatus.(*v1alpha1.BootstrapStatus).Status().SelfHostedControlPlane { - logger.Print("skipped as running self-hosted control plane") + logger.Info("skipped as running self-hosted control plane") continue } @@ -136,7 +138,7 @@ func (ctrl *ManifestApplyController) Run(ctx context.Context, r controller.Runti return fmt.Errorf("error loading kubeconfig: %w", err) } - kubeconfig.WarningHandler = rest.NewWarningWriter(logger.Writer(), rest.WarningWriterOptions{ + kubeconfig.WarningHandler = rest.NewWarningWriter(logging.NewWriter(logger, zapcore.WarnLevel), rest.WarningWriterOptions{ Deduplicate: true, }) @@ -175,7 +177,7 @@ func (ctrl *ManifestApplyController) Run(ctx context.Context, r controller.Runti } } -func (ctrl *ManifestApplyController) etcdLock(ctx context.Context, logger *log.Logger, f func() error) error { +func (ctrl *ManifestApplyController) etcdLock(ctx context.Context, logger *zap.Logger, f func() error) error { etcdClient, err := etcd.NewLocalClient() if err != nil { return fmt.Errorf("error creating etcd client: %w", err) @@ -192,13 +194,13 @@ func (ctrl *ManifestApplyController) etcdLock(ctx context.Context, logger *log.L mutex := concurrency.NewMutex(session, constants.EtcdTalosManifestApplyMutex) - logger.Printf("waiting for mutex") + logger.Debug("waiting for mutex") if err := mutex.Lock(ctx); err != nil { return fmt.Errorf("error acquiring mutex: %w", err) } - logger.Printf("mutex acquired") + logger.Debug("mutex acquired") defer mutex.Unlock(ctx) //nolint:errcheck @@ -206,7 +208,7 @@ func (ctrl *ManifestApplyController) etcdLock(ctx context.Context, logger *log.L } //nolint:gocyclo -func (ctrl *ManifestApplyController) apply(ctx context.Context, logger *log.Logger, mapper *restmapper.DeferredDiscoveryRESTMapper, dyn dynamic.Interface, manifests resource.List) error { +func (ctrl *ManifestApplyController) apply(ctx context.Context, logger *zap.Logger, mapper *restmapper.DeferredDiscoveryRESTMapper, dyn dynamic.Interface, manifests resource.List) error { // flatten list of objects to be applied objects := make([]*unstructured.Unstructured, 0, len(manifests.Items)) @@ -287,7 +289,7 @@ func (ctrl *ManifestApplyController) apply(ctx context.Context, logger *log.Logg return fmt.Errorf("error creating %s: %w", objName, err) } } else { - logger.Printf("created %s", objName) + logger.Sugar().Infof("created %s", objName) } } diff --git a/internal/app/machined/pkg/controllers/k8s/manifest_test.go b/internal/app/machined/pkg/controllers/k8s/manifest_test.go index cdc89e84ab..e12afb0575 100644 --- a/internal/app/machined/pkg/controllers/k8s/manifest_test.go +++ b/internal/app/machined/pkg/controllers/k8s/manifest_test.go @@ -22,6 +22,7 @@ import ( "github.com/talos-systems/go-retry/retry" k8sctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/k8s" + "github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/resources/config" "github.com/talos-systems/talos/pkg/resources/k8s" @@ -47,9 +48,7 @@ func (suite *ManifestSuite) SetupTest() { var err error - logger := log.New(log.Writer(), "controller-runtime: ", log.Flags()) - - suite.runtime, err = runtime.NewRuntime(suite.state, logger) + suite.runtime, err = runtime.NewRuntime(suite.state, logging.Wrap(log.Writer())) suite.Require().NoError(err) suite.Require().NoError(suite.runtime.RegisterController(&k8sctrl.ManifestController{})) diff --git a/internal/app/machined/pkg/controllers/k8s/render_secrets_static_pod.go b/internal/app/machined/pkg/controllers/k8s/render_secrets_static_pod.go index 5c5109599b..5dce793fdb 100644 --- a/internal/app/machined/pkg/controllers/k8s/render_secrets_static_pod.go +++ b/internal/app/machined/pkg/controllers/k8s/render_secrets_static_pod.go @@ -9,7 +9,6 @@ import ( "context" "fmt" "io/ioutil" - "log" "os" "path/filepath" stdlibtemplate "text/template" @@ -19,6 +18,7 @@ import ( "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" "github.com/talos-systems/crypto/x509" + "go.uber.org/zap" "github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/resources/k8s" @@ -69,7 +69,7 @@ func (ctrl *RenderSecretsStaticPodController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint:gocyclo,cyclop -func (ctrl *RenderSecretsStaticPodController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *RenderSecretsStaticPodController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { for { select { case <-ctx.Done(): diff --git a/internal/app/machined/pkg/controllers/network/address_config.go b/internal/app/machined/pkg/controllers/network/address_config.go index e82254f067..40920646d5 100644 --- a/internal/app/machined/pkg/controllers/network/address_config.go +++ b/internal/app/machined/pkg/controllers/network/address_config.go @@ -7,7 +7,6 @@ package network import ( "context" "fmt" - "log" "net" "sort" "strings" @@ -17,6 +16,7 @@ import ( "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" "github.com/talos-systems/go-procfs/procfs" + "go.uber.org/zap" "inet.af/netaddr" talosconfig "github.com/talos-systems/talos/pkg/machinery/config" @@ -60,7 +60,7 @@ func (ctrl *AddressConfigController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint: gocyclo, cyclop -func (ctrl *AddressConfigController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *AddressConfigController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { // apply defaults for the loopback interface once defaultTouchedIDs, err := ctrl.apply(ctx, r, ctrl.loopbackDefaults()) if err != nil { @@ -203,7 +203,7 @@ func (ctrl *AddressConfigController) loopbackDefaults() []network.AddressSpecSpe } //nolint: gocyclo -func (ctrl *AddressConfigController) parseCmdline(logger *log.Logger) (address network.AddressSpecSpec) { +func (ctrl *AddressConfigController) parseCmdline(logger *zap.Logger) (address network.AddressSpecSpec) { if ctrl.Cmdline == nil { return } @@ -227,7 +227,7 @@ func (ctrl *AddressConfigController) parseCmdline(logger *log.Logger) (address n address.Address.IP, err = netaddr.ParseIP(fields[0]) if err != nil { - logger.Printf("ignoring cmdline address parse failure: %s", err) + logger.Info("ignoring cmdline address parse failure", zap.Error(err)) return } @@ -235,7 +235,7 @@ func (ctrl *AddressConfigController) parseCmdline(logger *log.Logger) (address n if len(fields) >= 4 { netmask, err := netaddr.ParseIP(fields[3]) if err != nil { - logger.Printf("ignoring cmdline netmask parse failure: %s", err) + logger.Info("ignoring cmdline netmask parse failure", zap.Error(err)) return } @@ -280,7 +280,7 @@ func (ctrl *AddressConfigController) parseCmdline(logger *log.Logger) (address n return address } -func (ctrl *AddressConfigController) parseMachineConfiguration(logger *log.Logger, cfgProvider talosconfig.Provider) (addresses []network.AddressSpecSpec) { +func (ctrl *AddressConfigController) parseMachineConfiguration(logger *zap.Logger, cfgProvider talosconfig.Provider) (addresses []network.AddressSpecSpec) { for _, device := range cfgProvider.Machine().Network().Devices() { if device.Ignore() { continue @@ -289,7 +289,7 @@ func (ctrl *AddressConfigController) parseMachineConfiguration(logger *log.Logge if device.CIDR() != "" { ipPrefix, err := netaddr.ParseIPPrefix(device.CIDR()) if err != nil { - logger.Printf("skipping address %q on interface %q: %s", device.CIDR(), device.Interface(), err) + logger.Info(fmt.Sprintf("skipping address %q on interface %q", device.CIDR(), device.Interface()), zap.Error(err)) continue } @@ -315,7 +315,7 @@ func (ctrl *AddressConfigController) parseMachineConfiguration(logger *log.Logge if vlan.CIDR() != "" { ipPrefix, err := netaddr.ParseIPPrefix(vlan.CIDR()) if err != nil { - logger.Printf("skipping address %q on interface %q vlan %d: %s", device.CIDR(), device.Interface(), vlan.ID(), err) + logger.Info(fmt.Sprintf("skipping address %q on interface %q vlan %d", device.CIDR(), device.Interface(), vlan.ID()), zap.Error(err)) continue } diff --git a/internal/app/machined/pkg/controllers/network/address_config_test.go b/internal/app/machined/pkg/controllers/network/address_config_test.go index 5af53188d3..c59f72b186 100644 --- a/internal/app/machined/pkg/controllers/network/address_config_test.go +++ b/internal/app/machined/pkg/controllers/network/address_config_test.go @@ -26,6 +26,7 @@ import ( "github.com/talos-systems/go-retry/retry" netctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/network" + "github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1" "github.com/talos-systems/talos/pkg/resources/config" "github.com/talos-systems/talos/pkg/resources/network" @@ -51,9 +52,7 @@ func (suite *AddressConfigSuite) SetupTest() { var err error - logger := log.New(log.Writer(), "controller-runtime: ", log.Flags()) - - suite.runtime, err = runtime.NewRuntime(suite.state, logger) + suite.runtime, err = runtime.NewRuntime(suite.state, logging.Wrap(log.Writer())) suite.Require().NoError(err) } diff --git a/internal/app/machined/pkg/controllers/network/address_merge.go b/internal/app/machined/pkg/controllers/network/address_merge.go index 37898bd683..4873746056 100644 --- a/internal/app/machined/pkg/controllers/network/address_merge.go +++ b/internal/app/machined/pkg/controllers/network/address_merge.go @@ -7,10 +7,10 @@ package network import ( "context" "fmt" - "log" "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" + "go.uber.org/zap" "github.com/talos-systems/talos/pkg/resources/network" ) @@ -55,7 +55,7 @@ func (ctrl *AddressMergeController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint: gocyclo -func (ctrl *AddressMergeController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *AddressMergeController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { for { select { case <-ctx.Done(): diff --git a/internal/app/machined/pkg/controllers/network/address_merge_test.go b/internal/app/machined/pkg/controllers/network/address_merge_test.go index a7da7c2e71..bcd7b68bec 100644 --- a/internal/app/machined/pkg/controllers/network/address_merge_test.go +++ b/internal/app/machined/pkg/controllers/network/address_merge_test.go @@ -23,6 +23,7 @@ import ( "inet.af/netaddr" netctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/network" + "github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/resources/network" "github.com/talos-systems/talos/pkg/resources/network/nethelpers" ) @@ -46,9 +47,7 @@ func (suite *AddressMergeSuite) SetupTest() { var err error - logger := log.New(log.Writer(), "controller-runtime: ", log.Flags()) - - suite.runtime, err = runtime.NewRuntime(suite.state, logger) + suite.runtime, err = runtime.NewRuntime(suite.state, logging.Wrap(log.Writer())) suite.Require().NoError(err) suite.Require().NoError(suite.runtime.RegisterController(&netctrl.AddressMergeController{})) diff --git a/internal/app/machined/pkg/controllers/network/address_spec.go b/internal/app/machined/pkg/controllers/network/address_spec.go index 0b2c8a2eed..6d7c69313b 100644 --- a/internal/app/machined/pkg/controllers/network/address_spec.go +++ b/internal/app/machined/pkg/controllers/network/address_spec.go @@ -7,12 +7,12 @@ package network import ( "context" "fmt" - "log" "net" "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" "github.com/jsimonetti/rtnetlink" + "go.uber.org/zap" "golang.org/x/sys/unix" "inet.af/netaddr" @@ -47,7 +47,7 @@ func (ctrl *AddressSpecController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint: gocyclo -func (ctrl *AddressSpecController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *AddressSpecController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { watchCh := make(chan struct{}) // watch link changes as some address might need to be re-applied if the link appears @@ -144,7 +144,7 @@ func findAddress(addrs []rtnetlink.AddressMessage, linkIndex uint32, ipPrefix ne } //nolint:gocyclo -func (ctrl *AddressSpecController) syncAddress(ctx context.Context, r controller.Runtime, logger *log.Logger, conn *rtnetlink.Conn, +func (ctrl *AddressSpecController) syncAddress(ctx context.Context, r controller.Runtime, logger *zap.Logger, conn *rtnetlink.Conn, links []rtnetlink.LinkMessage, addrs []rtnetlink.AddressMessage, address *network.AddressSpec) error { linkIndex := resolveLinkName(links, address.Status().LinkName) @@ -165,7 +165,7 @@ func (ctrl *AddressSpecController) syncAddress(ctx context.Context, r controller return fmt.Errorf("error removing address: %w", err) } - logger.Printf("removed address %s from %q", address.Status().Address, address.Status().LinkName) + logger.Sugar().Infof("removed address %s from %q", address.Status().Address, address.Status().LinkName) } // now remove finalizer as address was deleted @@ -190,7 +190,7 @@ func (ctrl *AddressSpecController) syncAddress(ctx context.Context, r controller return fmt.Errorf("error removing address: %w", err) } - logger.Printf("removed address %s from %q", address.Status().Address, address.Status().LinkName) + logger.Sugar().Infof("removed address %s from %q", address.Status().Address, address.Status().LinkName) } // add address @@ -210,7 +210,7 @@ func (ctrl *AddressSpecController) syncAddress(ctx context.Context, r controller return fmt.Errorf("error adding address: %w", err) } - logger.Printf("assigned address %s to %q", address.Status().Address, address.Status().LinkName) + logger.Sugar().Infof("assigned address %s to %q", address.Status().Address, address.Status().LinkName) } return nil diff --git a/internal/app/machined/pkg/controllers/network/address_spec_test.go b/internal/app/machined/pkg/controllers/network/address_spec_test.go index ef4f898bd9..05ab0f546a 100644 --- a/internal/app/machined/pkg/controllers/network/address_spec_test.go +++ b/internal/app/machined/pkg/controllers/network/address_spec_test.go @@ -26,6 +26,7 @@ import ( "inet.af/netaddr" netctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/network" + "github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/resources/network" "github.com/talos-systems/talos/pkg/resources/network/nethelpers" ) @@ -49,9 +50,7 @@ func (suite *AddressSpecSuite) SetupTest() { var err error - logger := log.New(log.Writer(), "controller-runtime: ", log.Flags()) - - suite.runtime, err = runtime.NewRuntime(suite.state, logger) + suite.runtime, err = runtime.NewRuntime(suite.state, logging.Wrap(log.Writer())) suite.Require().NoError(err) suite.Require().NoError(suite.runtime.RegisterController(&netctrl.AddressSpecController{})) diff --git a/internal/app/machined/pkg/controllers/network/address_status.go b/internal/app/machined/pkg/controllers/network/address_status.go index b9e5c8d7e6..48c3e0a6d4 100644 --- a/internal/app/machined/pkg/controllers/network/address_status.go +++ b/internal/app/machined/pkg/controllers/network/address_status.go @@ -7,11 +7,11 @@ package network import ( "context" "fmt" - "log" "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" "github.com/jsimonetti/rtnetlink" + "go.uber.org/zap" "golang.org/x/sys/unix" "inet.af/netaddr" @@ -46,7 +46,7 @@ func (ctrl *AddressStatusController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint:gocyclo -func (ctrl *AddressStatusController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *AddressStatusController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { watchCh := make(chan struct{}) watcher, err := watch.NewRtNetlink(ctx, watchCh, unix.RTMGRP_LINK|unix.RTMGRP_IPV4_IFADDR|unix.RTMGRP_IPV6_IFADDR) diff --git a/internal/app/machined/pkg/controllers/network/address_status_test.go b/internal/app/machined/pkg/controllers/network/address_status_test.go index 433fcb26ab..88e6a6dc5b 100644 --- a/internal/app/machined/pkg/controllers/network/address_status_test.go +++ b/internal/app/machined/pkg/controllers/network/address_status_test.go @@ -22,6 +22,7 @@ import ( "github.com/talos-systems/go-retry/retry" netctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/network" + "github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/resources/network" ) @@ -44,9 +45,7 @@ func (suite *AddressStatusSuite) SetupTest() { var err error - logger := log.New(log.Writer(), "controller-runtime: ", log.Flags()) - - suite.runtime, err = runtime.NewRuntime(suite.state, logger) + suite.runtime, err = runtime.NewRuntime(suite.state, logging.Wrap(log.Writer())) suite.Require().NoError(err) suite.Require().NoError(suite.runtime.RegisterController(&netctrl.AddressStatusController{})) diff --git a/internal/app/machined/pkg/controllers/network/link_status.go b/internal/app/machined/pkg/controllers/network/link_status.go index e958def8ec..4c1ffe0aa0 100644 --- a/internal/app/machined/pkg/controllers/network/link_status.go +++ b/internal/app/machined/pkg/controllers/network/link_status.go @@ -8,13 +8,13 @@ import ( "context" "errors" "fmt" - "log" "os" "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" "github.com/jsimonetti/rtnetlink" "github.com/mdlayher/ethtool" + "go.uber.org/zap" "golang.org/x/sys/unix" "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/network/watch" @@ -46,7 +46,7 @@ func (ctrl *LinkStatusController) Outputs() []controller.Output { } // Run implements controller.Controller interface. -func (ctrl *LinkStatusController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *LinkStatusController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { // create watch connections to rtnetlink and ethtool via genetlink // these connections are used only to join multicast groups and receive notifications on changes // other connections are used to send requests and receive responses, as we can't mix the notifications and request/responses diff --git a/internal/app/machined/pkg/controllers/network/link_status_test.go b/internal/app/machined/pkg/controllers/network/link_status_test.go index 37f9cb4aa4..0cdb39fcf5 100644 --- a/internal/app/machined/pkg/controllers/network/link_status_test.go +++ b/internal/app/machined/pkg/controllers/network/link_status_test.go @@ -25,6 +25,7 @@ import ( "golang.org/x/sys/unix" netctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/network" + "github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/resources/network" "github.com/talos-systems/talos/pkg/resources/network/nethelpers" ) @@ -48,9 +49,7 @@ func (suite *LinkStatusSuite) SetupTest() { var err error - logger := log.New(log.Writer(), "controller-runtime: ", log.Flags()) - - suite.runtime, err = runtime.NewRuntime(suite.state, logger) + suite.runtime, err = runtime.NewRuntime(suite.state, logging.Wrap(log.Writer())) suite.Require().NoError(err) suite.Require().NoError(suite.runtime.RegisterController(&netctrl.LinkStatusController{})) diff --git a/internal/app/machined/pkg/controllers/secrets/etcd.go b/internal/app/machined/pkg/controllers/secrets/etcd.go index 771288b5f7..c3f04f7ae4 100644 --- a/internal/app/machined/pkg/controllers/secrets/etcd.go +++ b/internal/app/machined/pkg/controllers/secrets/etcd.go @@ -7,12 +7,12 @@ package secrets import ( "context" "fmt" - "log" "github.com/AlekSi/pointer" "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" + "go.uber.org/zap" "github.com/talos-systems/talos/internal/pkg/etcd" "github.com/talos-systems/talos/pkg/resources/secrets" @@ -65,7 +65,7 @@ func (ctrl *EtcdController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint:gocyclo -func (ctrl *EtcdController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *EtcdController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { for { select { case <-ctx.Done(): diff --git a/internal/app/machined/pkg/controllers/secrets/kubernetes.go b/internal/app/machined/pkg/controllers/secrets/kubernetes.go index 273e2e43f8..43e2533abb 100644 --- a/internal/app/machined/pkg/controllers/secrets/kubernetes.go +++ b/internal/app/machined/pkg/controllers/secrets/kubernetes.go @@ -8,7 +8,6 @@ import ( "bytes" "context" "fmt" - "log" "net" "net/url" "time" @@ -18,6 +17,7 @@ import ( "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" "github.com/talos-systems/crypto/x509" + "go.uber.org/zap" "github.com/talos-systems/talos/internal/pkg/kubeconfig" "github.com/talos-systems/talos/pkg/machinery/config" @@ -77,7 +77,7 @@ func (ctrl *KubernetesController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint:gocyclo -func (ctrl *KubernetesController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *KubernetesController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { refreshTicker := time.NewTicker(KubernetesCertificateValidityDuration / 2) defer refreshTicker.Stop() diff --git a/internal/app/machined/pkg/controllers/secrets/root.go b/internal/app/machined/pkg/controllers/secrets/root.go index 8bacb75b44..bd58683b4b 100644 --- a/internal/app/machined/pkg/controllers/secrets/root.go +++ b/internal/app/machined/pkg/controllers/secrets/root.go @@ -7,12 +7,12 @@ package secrets import ( "context" "fmt" - "log" "github.com/AlekSi/pointer" "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" + "go.uber.org/zap" talosconfig "github.com/talos-systems/talos/pkg/machinery/config" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine" @@ -59,7 +59,7 @@ func (ctrl *RootController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint:gocyclo -func (ctrl *RootController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *RootController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { for { select { case <-ctx.Done(): diff --git a/internal/app/machined/pkg/controllers/time/sync.go b/internal/app/machined/pkg/controllers/time/sync.go index 9036830af1..9ccbb7d0dc 100644 --- a/internal/app/machined/pkg/controllers/time/sync.go +++ b/internal/app/machined/pkg/controllers/time/sync.go @@ -7,13 +7,13 @@ package time import ( "context" "fmt" - "log" "sync" "github.com/AlekSi/pointer" "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" + "go.uber.org/zap" v1alpha1runtime "github.com/talos-systems/talos/internal/app/machined/pkg/runtime" "github.com/talos-systems/talos/internal/pkg/ntp" @@ -64,14 +64,14 @@ type NTPSyncer interface { } // NewNTPSyncerFunc function allows to replace ntp.Syncer with the mock. -type NewNTPSyncerFunc func(*log.Logger, []string) NTPSyncer +type NewNTPSyncerFunc func(*zap.Logger, []string) NTPSyncer // Run implements controller.Controller interface. // //nolint:gocyclo,cyclop -func (ctrl *SyncController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *SyncController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { if ctrl.NewNTPSyncer == nil { - ctrl.NewNTPSyncer = func(logger *log.Logger, timeServers []string) NTPSyncer { + ctrl.NewNTPSyncer = func(logger *zap.Logger, timeServers []string) NTPSyncer { return ntp.NewSyncer(logger, timeServers) } } diff --git a/internal/app/machined/pkg/controllers/time/sync_test.go b/internal/app/machined/pkg/controllers/time/sync_test.go index 19e1d045be..1675166fd2 100644 --- a/internal/app/machined/pkg/controllers/time/sync_test.go +++ b/internal/app/machined/pkg/controllers/time/sync_test.go @@ -20,9 +20,11 @@ import ( "github.com/cosi-project/runtime/pkg/state/impl/namespaced" "github.com/stretchr/testify/suite" "github.com/talos-systems/go-retry/retry" + "go.uber.org/zap" timectrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/time" v1alpha1runtime "github.com/talos-systems/talos/internal/app/machined/pkg/runtime" + "github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1" "github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/resources/config" @@ -52,7 +54,7 @@ func (suite *SyncSuite) SetupTest() { var err error - logger := log.New(log.Writer(), "controller-runtime: ", log.Flags()) + logger := logging.Wrap(log.Writer()) suite.runtime, err = runtime.NewRuntime(suite.state, logger) suite.Require().NoError(err) @@ -326,7 +328,7 @@ func (suite *SyncSuite) TearDownTest() { suite.Assert().NoError(err) } -func (suite *SyncSuite) newMockSyncer(logger *log.Logger, servers []string) timectrl.NTPSyncer { +func (suite *SyncSuite) newMockSyncer(logger *zap.Logger, servers []string) timectrl.NTPSyncer { suite.syncerMu.Lock() defer suite.syncerMu.Unlock() @@ -380,7 +382,7 @@ func (mock *mockSyncer) SetTimeServers(servers []string) { mock.timeServers = append([]string(nil), servers...) } -func newMockSyncer(_ *log.Logger, servers []string) *mockSyncer { +func newMockSyncer(_ *zap.Logger, servers []string) *mockSyncer { return &mockSyncer{ timeServers: append([]string(nil), servers...), syncedCh: make(chan struct{}, 1), diff --git a/internal/app/machined/pkg/controllers/v1alpha1/boostrap_status.go b/internal/app/machined/pkg/controllers/v1alpha1/boostrap_status.go index aab0d5b568..003e440c6f 100644 --- a/internal/app/machined/pkg/controllers/v1alpha1/boostrap_status.go +++ b/internal/app/machined/pkg/controllers/v1alpha1/boostrap_status.go @@ -7,13 +7,13 @@ package v1alpha1 import ( "context" "fmt" - "log" "github.com/AlekSi/pointer" "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" clientv3 "go.etcd.io/etcd/client/v3" + "go.uber.org/zap" "github.com/talos-systems/talos/internal/app/machined/pkg/runtime" "github.com/talos-systems/talos/internal/pkg/etcd" @@ -54,7 +54,7 @@ func (ctrl *BootstrapStatusController) Outputs() []controller.Output { } // Run implements controller.Controller interface. -func (ctrl *BootstrapStatusController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *BootstrapStatusController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { for { select { case <-ctx.Done(): @@ -82,7 +82,7 @@ func (ctrl *BootstrapStatusController) Run(ctx context.Context, r controller.Run } } -func (ctrl *BootstrapStatusController) readInitialized(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *BootstrapStatusController) readInitialized(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { etcdClient, err := etcd.NewLocalClient() if err != nil { return fmt.Errorf("error creating etcd client: %w", err) @@ -106,7 +106,7 @@ func (ctrl *BootstrapStatusController) readInitialized(ctx context.Context, r co } if resp.Count == 0 || string(resp.Kvs[0].Value) != "true" { - logger.Printf("bootkube initialized status not found") + logger.Info("bootkube initialized status not found") return r.Modify(ctx, v1alpha1.NewBootstrapStatus(), func(r resource.Resource) error { r.(*v1alpha1.BootstrapStatus).Status().SelfHostedControlPlane = false @@ -115,7 +115,7 @@ func (ctrl *BootstrapStatusController) readInitialized(ctx context.Context, r co }) } - logger.Printf("found bootkube initialized status in etcd") + logger.Info("found bootkube initialized status in etcd") if err = r.Modify(ctx, v1alpha1.NewBootstrapStatus(), func(r resource.Resource) error { r.(*v1alpha1.BootstrapStatus).Status().SelfHostedControlPlane = true diff --git a/internal/app/machined/pkg/controllers/v1alpha1/service.go b/internal/app/machined/pkg/controllers/v1alpha1/service.go index 1671948a65..f12efc26f0 100644 --- a/internal/app/machined/pkg/controllers/v1alpha1/service.go +++ b/internal/app/machined/pkg/controllers/v1alpha1/service.go @@ -6,12 +6,13 @@ package v1alpha1 import ( "context" - "log" + "fmt" "sync" "github.com/cosi-project/runtime/pkg/controller" "github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/state" + "go.uber.org/zap" "github.com/talos-systems/talos/internal/app/machined/pkg/runtime" "github.com/talos-systems/talos/pkg/machinery/api/machine" @@ -46,7 +47,7 @@ func (ctrl *ServiceController) Outputs() []controller.Output { // Run implements controller.Controller interface. // //nolint:gocyclo -func (ctrl *ServiceController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error { +func (ctrl *ServiceController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { var wg sync.WaitGroup wg.Add(1) @@ -82,11 +83,11 @@ func (ctrl *ServiceController) Run(ctx context.Context, r controller.Runtime, lo return nil }); err != nil { - logger.Printf("failed creating service resource %s: %s", service, err) + logger.Info(fmt.Sprintf("failed creating service resource %s", service), zap.Error(err)) } default: if err := r.Destroy(ctx, service.Metadata()); err != nil && !state.IsNotFoundError(err) { - logger.Printf("failed destroying service resource %s: %s", service, err) + logger.Info(fmt.Sprintf("failed destroying service resource %s", service), zap.Error(err)) } } } diff --git a/internal/app/machined/pkg/runtime/v1alpha2/v1alpha2_controller.go b/internal/app/machined/pkg/runtime/v1alpha2/v1alpha2_controller.go index c30f3416c5..a597bf7a9d 100644 --- a/internal/app/machined/pkg/runtime/v1alpha2/v1alpha2_controller.go +++ b/internal/app/machined/pkg/runtime/v1alpha2/v1alpha2_controller.go @@ -6,11 +6,11 @@ package v1alpha2 import ( "context" - "log" "github.com/cosi-project/runtime/pkg/controller" osruntime "github.com/cosi-project/runtime/pkg/controller/runtime" "github.com/talos-systems/go-procfs/procfs" + "go.uber.org/zap/zapcore" "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/config" "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/k8s" @@ -19,6 +19,7 @@ import ( "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/time" "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/v1alpha1" "github.com/talos-systems/talos/internal/app/machined/pkg/runtime" + "github.com/talos-systems/talos/pkg/logging" ) // Controller implements runtime.V1alpha2Controller. @@ -39,7 +40,10 @@ func NewController(v1alpha1Runtime runtime.Runtime, loggingManager runtime.Loggi return nil, err } - logger := log.New(logWriter, "", log.LstdFlags|log.Lmsgprefix) + logger := logging.ZapLogger( + logging.NewLogDestination(logWriter, zapcore.DebugLevel, logging.WithColoredLevels()), + logging.NewLogDestination(logging.StdWriter, zapcore.InfoLevel, logging.WithoutTimestamp(), logging.WithoutLogLevels()), + ).With(logging.Component("controller-runtime")) ctrl.controllerRuntime, err = osruntime.NewRuntime(v1alpha1Runtime.State().V1Alpha2().Resources(), logger) diff --git a/internal/pkg/ntp/ntp.go b/internal/pkg/ntp/ntp.go index 1f636d09cc..79511499d4 100644 --- a/internal/pkg/ntp/ntp.go +++ b/internal/pkg/ntp/ntp.go @@ -9,7 +9,6 @@ import ( "bytes" "context" "fmt" - "log" "math/bits" "math/rand" "net" @@ -20,13 +19,14 @@ import ( "github.com/beevik/ntp" "github.com/u-root/u-root/pkg/rtc" + "go.uber.org/zap" "github.com/talos-systems/talos/internal/pkg/timex" ) // Syncer performs time sync via NTP on schedule. type Syncer struct { - logger *log.Logger + logger *zap.Logger timeServersMu sync.Mutex timeServers []string @@ -47,7 +47,7 @@ type Syncer struct { } // NewSyncer creates new Syncer with default configuration. -func NewSyncer(logger *log.Logger, timeServers []string) *Syncer { +func NewSyncer(logger *zap.Logger, timeServers []string) *Syncer { syncer := &Syncer{ logger: logger, @@ -133,7 +133,7 @@ func (syncer *Syncer) Run(ctx context.Context) { RTCClock, err = rtc.OpenRTC() if err != nil { - syncer.logger.Printf("failure opening RTC, ignored: %s", err) + syncer.logger.Error("failure opening RTC, ignored", zap.Error(err)) } }) @@ -164,7 +164,7 @@ func (syncer *Syncer) Run(ctx context.Context) { syncer.timeSyncNotified = true } } else { - syncer.logger.Printf("error adjusting time: %s", err) + syncer.logger.Error("error adjusting time", zap.Error(err)) } } @@ -185,7 +185,7 @@ func (syncer *Syncer) query(ctx context.Context) (lastSyncServer string, resp *n if lastSyncServer != "" { resp, err = syncer.queryServer(lastSyncServer) if err != nil { - syncer.logger.Printf("ntp query error with server %q: %v", lastSyncServer, err) + syncer.logger.Error(fmt.Sprintf("ntp query error with server %q", lastSyncServer), zap.Error(err)) failedServer = lastSyncServer lastSyncServer = "" @@ -217,7 +217,7 @@ func (syncer *Syncer) query(ctx context.Context) (lastSyncServer string, resp *n resp, err = syncer.queryServer(server) if err != nil { - syncer.logger.Printf("ntp query error with server %q: %v", server, err) + syncer.logger.Error(fmt.Sprintf("ntp query error with server %q", server), zap.Error(err)) err = nil } else { syncer.setLastSyncServer(server) @@ -237,7 +237,7 @@ func (syncer *Syncer) resolveServers(ctx context.Context) ([]string, error) { for _, server := range syncer.getTimeServers() { ips, err := net.LookupIP(server) if err != nil { - syncer.logger.Printf("failed looking up %q: %s, ignored", server, err) + syncer.logger.Warn(fmt.Sprintf("failed looking up %q, ignored", server), zap.Error(err)) } for _, ip := range ips { @@ -326,7 +326,7 @@ func (syncer *Syncer) adjustTime(offset time.Duration, leapSecond ntp.LeapIndica fmt.Println(&buf, ", error was %s", err) } - syncer.logger.Println(buf.String()) + syncer.logger.Info(buf.String()) if err == nil { if offset < -EpochLimit || offset > EpochLimit { @@ -340,9 +340,9 @@ func (syncer *Syncer) adjustTime(offset time.Duration, leapSecond ntp.LeapIndica if jump { if RTCClock != nil { if rtcErr := RTCClock.Set(time.Now().Add(offset)); rtcErr != nil { - syncer.logger.Printf("error syncing RTC: %s", rtcErr) + syncer.logger.Error("error syncing RTC", zap.Error(rtcErr)) } else { - syncer.logger.Printf("synchronized RTC with system clock") + syncer.logger.Info("synchronized RTC with system clock") } } } diff --git a/internal/pkg/ntp/ntp_test.go b/internal/pkg/ntp/ntp_test.go index 47b16ae1d0..ee9a14b10f 100644 --- a/internal/pkg/ntp/ntp_test.go +++ b/internal/pkg/ntp/ntp_test.go @@ -16,9 +16,11 @@ import ( beevikntp "github.com/beevik/ntp" "github.com/stretchr/testify/suite" "github.com/talos-systems/go-retry/retry" + "go.uber.org/zap" "github.com/talos-systems/talos/internal/pkg/ntp" "github.com/talos-systems/talos/internal/pkg/timex" + "github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/machinery/constants" ) @@ -135,7 +137,7 @@ func (suite *NTPSuite) fakeQuery(host string) (resp *beevikntp.Response, err err } func (suite *NTPSuite) TestSync() { - syncer := ntp.NewSyncer(log.New(log.Writer(), "ntp ", log.LstdFlags), []string{constants.DefaultNTPServer}) + syncer := ntp.NewSyncer(logging.Wrap(log.Writer()).With(zap.String("controller", "ntp")), []string{constants.DefaultNTPServer}) syncer.AdjustTime = suite.adjustSystemClock syncer.CurrentTime = suite.getSystemClock @@ -165,7 +167,7 @@ func (suite *NTPSuite) TestSync() { } func (suite *NTPSuite) TestSyncContinuous() { - syncer := ntp.NewSyncer(log.New(log.Writer(), "ntp ", log.LstdFlags), []string{"127.0.0.3"}) + syncer := ntp.NewSyncer(logging.Wrap(log.Writer()).With(zap.String("controller", "ntp")), []string{"127.0.0.3"}) syncer.AdjustTime = suite.adjustSystemClock syncer.CurrentTime = suite.getSystemClock @@ -211,7 +213,7 @@ func (suite *NTPSuite) TestSyncContinuous() { } func (suite *NTPSuite) TestSyncChangeTimeservers() { - syncer := ntp.NewSyncer(log.New(log.Writer(), "ntp ", log.LstdFlags), []string{"127.0.0.1"}) + syncer := ntp.NewSyncer(logging.Wrap(log.Writer()).With(zap.String("controller", "ntp")), []string{"127.0.0.1"}) syncer.AdjustTime = suite.adjustSystemClock syncer.CurrentTime = suite.getSystemClock @@ -249,7 +251,7 @@ func (suite *NTPSuite) TestSyncChangeTimeservers() { } func (suite *NTPSuite) TestSyncIterateTimeservers() { - syncer := ntp.NewSyncer(log.New(log.Writer(), "ntp ", log.LstdFlags), []string{"127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4"}) + syncer := ntp.NewSyncer(logging.Wrap(log.Writer()).With(zap.String("controller", "ntp")), []string{"127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4"}) syncer.AdjustTime = suite.adjustSystemClock syncer.CurrentTime = suite.getSystemClock @@ -300,7 +302,7 @@ func (suite *NTPSuite) TestSyncIterateTimeservers() { } func (suite *NTPSuite) TestSyncEpochChange() { - syncer := ntp.NewSyncer(log.New(log.Writer(), "ntp ", log.LstdFlags), []string{"127.0.0.5"}) + syncer := ntp.NewSyncer(logging.Wrap(log.Writer()).With(zap.String("controller", "ntp")), []string{"127.0.0.5"}) syncer.AdjustTime = suite.adjustSystemClock syncer.CurrentTime = suite.getSystemClock @@ -339,7 +341,7 @@ func (suite *NTPSuite) TestSyncEpochChange() { } func (suite *NTPSuite) TestSyncSwitchTimeservers() { - syncer := ntp.NewSyncer(log.New(log.Writer(), "ntp ", log.LstdFlags), []string{"127.0.0.6", "127.0.0.4"}) + syncer := ntp.NewSyncer(logging.Wrap(log.Writer()).With(zap.String("controller", "ntp")), []string{"127.0.0.6", "127.0.0.4"}) syncer.AdjustTime = suite.adjustSystemClock syncer.CurrentTime = suite.getSystemClock diff --git a/pkg/logging/logging.go b/pkg/logging/logging.go new file mode 100644 index 0000000000..82f35f966f --- /dev/null +++ b/pkg/logging/logging.go @@ -0,0 +1,6 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +// Package logging provides logging primitives. +package logging diff --git a/pkg/logging/zap.go b/pkg/logging/zap.go new file mode 100644 index 0000000000..0d768d55f6 --- /dev/null +++ b/pkg/logging/zap.go @@ -0,0 +1,141 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package logging + +import ( + "io" + "log" + "strings" + + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +// LogWriter is a wrapper around zap.Logger that implements io.Writer interface. +type LogWriter struct { + dest *zap.Logger + level zapcore.Level +} + +// NewWriter creates new log zap log writer. +func NewWriter(l *zap.Logger, level zapcore.Level) io.Writer { + return &LogWriter{ + dest: l, + level: level, + } +} + +// Write implements io.Writer interface. +func (lw *LogWriter) Write(line []byte) (int, error) { + checked := lw.dest.Check(lw.level, strings.TrimSpace(string(line))) + if checked == nil { + return 0, nil + } + + checked.Write() + + return len(line), nil +} + +// LogWrapper wraps around standard logger. +type LogWrapper struct { + log *log.Logger +} + +// Write implements io.Writer interface. +func (lw *LogWrapper) Write(line []byte) (int, error) { + if lw.log == nil { + log.Print(string(line)) + } else { + lw.log.Print(string(line)) + } + + return len(line), nil +} + +// StdWriter creates a sync writer that writes all logs to the std logger. +var StdWriter = &LogWrapper{nil} + +// LogDestination defines logging destination Config. +type LogDestination struct { + // Level log level. + Level zap.AtomicLevel + writer io.Writer + config zapcore.EncoderConfig +} + +// EncoderOption defines a log destination encoder config setter. +type EncoderOption func(config *zapcore.EncoderConfig) + +// WithoutTimestamp disables timestamp. +func WithoutTimestamp() EncoderOption { + return func(config *zapcore.EncoderConfig) { + config.EncodeTime = nil + } +} + +// WithoutLogLevels disable log level. +func WithoutLogLevels() EncoderOption { + return func(config *zapcore.EncoderConfig) { + config.EncodeLevel = nil + } +} + +// WithColoredLevels enables log level colored output. +func WithColoredLevels() EncoderOption { + return func(config *zapcore.EncoderConfig) { + config.EncodeLevel = zapcore.CapitalColorLevelEncoder + } +} + +// NewLogDestination creates new log destination. +func NewLogDestination(writer io.Writer, logLevel zapcore.Level, options ...EncoderOption) *LogDestination { + config := zap.NewDevelopmentEncoderConfig() + config.ConsoleSeparator = " " + config.StacktraceKey = "error" + + for _, option := range options { + option(&config) + } + + return &LogDestination{ + Level: zap.NewAtomicLevelAt(logLevel), + config: config, + writer: writer, + } +} + +// Wrap is a simple helper to wrap io.Writer with default arguments. +func Wrap(writer io.Writer) *zap.Logger { + return ZapLogger( + NewLogDestination(writer, zapcore.DebugLevel), + ) +} + +// ZapLogger creates new default Zap Logger. +func ZapLogger(dests ...*LogDestination) *zap.Logger { + if len(dests) == 0 { + panic("at least one writer must be defined") + } + + cores := []zapcore.Core{} + + for _, dest := range dests { + consoleEncoder := zapcore.NewConsoleEncoder(dest.config) + + cores = append(cores, zapcore.NewCore(consoleEncoder, zapcore.AddSync(dest.writer), dest.Level)) + } + + core := zapcore.NewTee(cores...) + + logger := zap.New(core) + + return logger +} + +// Component helper for creating zap.Field. +func Component(name string) zapcore.Field { + return zap.String("component", name) +}