From 901467152e6857a2ac3a48f1a28afa0c54754cbf Mon Sep 17 00:00:00 2001 From: KsaweryZietara Date: Thu, 12 Dec 2024 09:25:11 +0100 Subject: [PATCH] Remove logrus --- cmd/broker/bindings_envtest_test.go | 9 +- cmd/broker/broker_suite_test.go | 8 +- common/deprovision/client.go | 10 +- common/hyperscaler/azure/client.go | 8 +- common/hyperscaler/azure/provider.go | 6 +- common/hyperscaler/azure/testing/testing.go | 5 +- docs/user/03-20-runtime-operations.md | 12 +- go.mod | 2 +- internal/broker/client.go | 25 ++-- internal/broker/labeler.go | 17 ++- internal/httputil/write_response.go | 6 +- internal/logger/spy_logger.go | 139 ------------------ internal/metricsv2/debuger.go | 8 +- internal/model.go | 7 +- .../process/deprovisioning/automock/step.go | 10 +- internal/provisioner/graphqlizer.go | 9 +- testing/e2e/provisioning/go.mod | 1 - testing/e2e/provisioning/go.sum | 1 - .../pkg/client/broker/broker_client.go | 44 +++--- .../client/broker/upgrade_broker_client.go | 12 +- .../pkg/client/runtime/runtime_client.go | 9 +- .../pkg/client/v1_client/configmap.go | 15 +- .../pkg/client/v1_client/secret.go | 11 +- .../test/e2e_provisioning_test.go | 6 +- .../provisioning/test/e2e_suspension_test.go | 6 +- .../e2e/provisioning/test/e2e_upgrade_test.go | 5 +- testing/e2e/provisioning/test/test_suite.go | 20 ++- .../provisioning/test/upgrade_test_suite.go | 4 +- 28 files changed, 137 insertions(+), 278 deletions(-) delete mode 100644 internal/logger/spy_logger.go diff --git a/cmd/broker/bindings_envtest_test.go b/cmd/broker/bindings_envtest_test.go index 0d7d829065..301605857b 100644 --- a/cmd/broker/bindings_envtest_test.go +++ b/cmd/broker/bindings_envtest_test.go @@ -31,7 +31,6 @@ import ( "github.com/kyma-project/kyma-environment-broker/internal/storage" "github.com/pivotal-cf/brokerapi/v8/domain" "github.com/pivotal-cf/brokerapi/v8/handlers" - "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" @@ -81,14 +80,8 @@ func TestCreateBindingEndpoint(t *testing.T) { Level: slog.LevelDebug, })) - logs := logrus.New() - logs.SetLevel(logrus.DebugLevel) - logs.SetFormatter(&logrus.JSONFormatter{ - TimestampFormat: time.RFC3339Nano, - }) - brokerLogger := lager.NewLogger("test") - brokerLogger.RegisterSink(lager.NewWriterSink(logs.Writer(), lager.DEBUG)) + brokerLogger.RegisterSink(lager.NewWriterSink(os.Stdout, lager.DEBUG)) //// schema sch := runtime.NewScheme() diff --git a/cmd/broker/broker_suite_test.go b/cmd/broker/broker_suite_test.go index 8f74c800c1..b2c3b2d885 100644 --- a/cmd/broker/broker_suite_test.go +++ b/cmd/broker/broker_suite_test.go @@ -53,7 +53,6 @@ import ( "github.com/pivotal-cf/brokerapi/v8/domain" "github.com/pivotal-cf/brokerapi/v8/domain/apiresponses" "github.com/pkg/errors" - "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" @@ -200,9 +199,6 @@ func NewBrokerSuiteTestWithConfig(t *testing.T, cfg *Config, version ...string) require.NoError(t, err) - logs := logrus.New() - logs.SetLevel(logrus.DebugLevel) - gardenerClient := gardener.NewDynamicFakeClient() provisionerClient := provisioner.NewFakeClientWithGardener(gardenerClient, "kcp-system") @@ -249,7 +245,7 @@ func NewBrokerSuiteTestWithConfig(t *testing.T, cfg *Config, version ...string) } ts.poller = &broker.TimerPoller{PollInterval: 3 * time.Millisecond, PollTimeout: 3 * time.Second, Log: ts.t.Log} - ts.CreateAPI(inputFactory, cfg, db, provisioningQueue, deprovisioningQueue, updateQueue, logs, log, k8sClientProvider, gardener.NewFakeClient(), eventBroker) + ts.CreateAPI(inputFactory, cfg, db, provisioningQueue, deprovisioningQueue, updateQueue, log, k8sClientProvider, gardener.NewFakeClient(), eventBroker) notificationFakeClient := notification.NewFakeClient() notificationBundleBuilder := notification.NewBundleBuilder(notificationFakeClient, cfg.Notification) @@ -366,7 +362,7 @@ func (s *BrokerSuiteTest) CallAPI(method string, path string, body string) *http return resp } -func (s *BrokerSuiteTest) CreateAPI(inputFactory broker.PlanValidator, cfg *Config, db storage.BrokerStorage, provisioningQueue *process.Queue, deprovisionQueue *process.Queue, updateQueue *process.Queue, logs logrus.FieldLogger, log *slog.Logger, skrK8sClientProvider *kubeconfig.FakeProvider, gardenerClient client.Client, eventBroker *event.PubSub) { +func (s *BrokerSuiteTest) CreateAPI(inputFactory broker.PlanValidator, cfg *Config, db storage.BrokerStorage, provisioningQueue *process.Queue, deprovisionQueue *process.Queue, updateQueue *process.Queue, log *slog.Logger, skrK8sClientProvider *kubeconfig.FakeProvider, gardenerClient client.Client, eventBroker *event.PubSub) { servicesConfig := map[string]broker.Service{ broker.KymaServiceName: { Description: "", diff --git a/common/deprovision/client.go b/common/deprovision/client.go index feeb0de3f1..020781a67f 100644 --- a/common/deprovision/client.go +++ b/common/deprovision/client.go @@ -2,10 +2,10 @@ package deprovision import ( "fmt" + "log/slog" "net/http" "time" - "github.com/sirupsen/logrus" "golang.org/x/oauth2/clientcredentials" ) @@ -17,7 +17,7 @@ type Client interface { } type DeprovisionClient struct { - log logrus.FieldLogger + log *slog.Logger URL string client *http.Client } @@ -34,7 +34,7 @@ func NewDeprovisionClient(parameters DeprovisionParameters) *DeprovisionClient { httpClientOAuth.Timeout = 30 * time.Second return &DeprovisionClient{ - log: logrus.WithField("client", "deprovision"), + log: slog.With("client", "deprovision"), URL: parameters.EndpointURL, client: httpClientOAuth, } @@ -45,7 +45,7 @@ func (c DeprovisionClient) DeprovisionRuntime(instanceID string) error { url := c.URL + "/oauth/v2/service_instances/" + instanceID + "?accepts_incomplete=true&service_id=faebbe18-0a84-11e5-ab14-d663bd873d97&plan_id=0c712d43-b1e6-470s-9fe5-8e1d552aa6a5" - c.log.Infof("url: %s", url) + c.log.Info(fmt.Sprintf("url: %s", url)) request, err := http.NewRequest("DELETE", url, nil) if err != nil { return fmt.Errorf("while creating the HTTP Delete request for deprovisioning: %w", err) @@ -65,7 +65,7 @@ func (c DeprovisionClient) DeprovisionRuntime(instanceID string) error { if response.StatusCode != http.StatusOK { return fmt.Errorf("calling %s returned %d (%s) status", request.URL.String(), response.StatusCode, response.Status) } - c.log.Infof("Deprovisioning request returned code: " + response.Status) + c.log.Info(fmt.Sprintf("Deprovisioning request returned code: %s", response.Status)) return err } diff --git a/common/hyperscaler/azure/client.go b/common/hyperscaler/azure/client.go index 5b1ac3e4ec..a9ff778644 100644 --- a/common/hyperscaler/azure/client.go +++ b/common/hyperscaler/azure/client.go @@ -3,10 +3,10 @@ package azure import ( "context" "fmt" + "log/slog" "github.com/Azure/azure-sdk-for-go/services/eventhub/mgmt/2017-04-01/eventhub" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2019-05-01/resources" - "github.com/sirupsen/logrus" ) const ( @@ -30,7 +30,7 @@ type Client struct { // the actual azure client eventHubNamespaceClient eventhub.NamespacesClient resourceGroupClient resources.GroupsClient - logger logrus.FieldLogger + logger *slog.Logger } type ResourceGroupDoesNotExistError struct { @@ -45,7 +45,7 @@ func (e ResourceGroupDoesNotExistError) Error() string { return e.message } -func NewAzureClient(namespaceClient eventhub.NamespacesClient, resourceGroupClient resources.GroupsClient, logger logrus.FieldLogger) *Client { +func NewAzureClient(namespaceClient eventhub.NamespacesClient, resourceGroupClient resources.GroupsClient, logger *slog.Logger) *Client { return &Client{ eventHubNamespaceClient: namespaceClient, resourceGroupClient: resourceGroupClient, @@ -82,7 +82,7 @@ func (nc *Client) DeleteResourceGroup(ctx context.Context, tags Tags) (resources if resourceGroup.Name == nil { return resources.GroupsDeleteFuture{}, fmt.Errorf("resource group name is nil") } - nc.logger.Infof("deleting resource group: %s", *resourceGroup.Name) + nc.logger.Info(fmt.Sprintf("deleting resource group: %s", *resourceGroup.Name)) future, err := nc.resourceGroupClient.Delete(ctx, *resourceGroup.Name) return future, err } diff --git a/common/hyperscaler/azure/provider.go b/common/hyperscaler/azure/provider.go index afa57fcbb6..287b51ce7a 100644 --- a/common/hyperscaler/azure/provider.go +++ b/common/hyperscaler/azure/provider.go @@ -2,17 +2,17 @@ package azure import ( "fmt" + "log/slog" "github.com/Azure/azure-sdk-for-go/services/eventhub/mgmt/2017-04-01/eventhub" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2019-05-01/resources" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/adal" "github.com/Azure/go-autorest/autorest/azure" - "github.com/sirupsen/logrus" ) type HyperscalerProvider interface { - GetClient(config *Config, logger logrus.FieldLogger) (Interface, error) + GetClient(config *Config, logger *slog.Logger) (Interface, error) } var _ HyperscalerProvider = (*azureProvider)(nil) @@ -24,7 +24,7 @@ func NewAzureProvider() HyperscalerProvider { } // GetClient gets a client for interacting with Azure -func (ac *azureProvider) GetClient(config *Config, logger logrus.FieldLogger) (Interface, error) { +func (ac *azureProvider) GetClient(config *Config, logger *slog.Logger) (Interface, error) { environment, err := config.Environment() if err != nil { diff --git a/common/hyperscaler/azure/testing/testing.go b/common/hyperscaler/azure/testing/testing.go index 1a4eff5b90..9daf03b7c3 100644 --- a/common/hyperscaler/azure/testing/testing.go +++ b/common/hyperscaler/azure/testing/testing.go @@ -3,12 +3,11 @@ package testing import ( "context" "fmt" + "log/slog" "github.com/Azure/azure-sdk-for-go/services/eventhub/mgmt/2017-04-01/eventhub" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2019-05-01/resources" "github.com/Azure/go-autorest/autorest" - "github.com/sirupsen/logrus" - "github.com/kyma-project/kyma-environment-broker/common/hyperscaler/azure" "github.com/kyma-project/kyma-environment-broker/internal/ptr" ) @@ -153,7 +152,7 @@ type FakeHyperscalerProvider struct { Err error } -func (ac *FakeHyperscalerProvider) GetClient(config *azure.Config, logger logrus.FieldLogger) (azure.Interface, error) { +func (ac *FakeHyperscalerProvider) GetClient(config *azure.Config, logger *slog.Logger) (azure.Interface, error) { return ac.Client, ac.Err } diff --git a/docs/user/03-20-runtime-operations.md b/docs/user/03-20-runtime-operations.md index 82ecf77de6..cdd114490f 100644 --- a/docs/user/03-20-runtime-operations.md +++ b/docs/user/03-20-runtime-operations.md @@ -60,7 +60,7 @@ You can configure SAP BTP, Kyma runtime operations by providing additional steps ```go type Step interface { Name() string - Run(operation internal.Operation, logger logrus.FieldLogger) (internal.Operation, time.Duration, error) + Run(operation internal.Operation, logger *slog.Logger) (internal.Operation, time.Duration, error) } ``` @@ -101,14 +101,14 @@ You can configure SAP BTP, Kyma runtime operations by providing additional steps import ( "encoding/json" + "fmt" + "log/slog" "net/http" "time" "github.com/kyma-incubator/compass/components/provisioner/pkg/gqlschema" "github.com/kyma-incubator/compass/components/kyma-environment-broker/internal" "github.com/kyma-incubator/compass/components/kyma-environment-broker/internal/storage" - - "github.com/sirupsen/logrus" ) type HelloWorldStep struct { @@ -133,7 +133,7 @@ You can configure SAP BTP, Kyma runtime operations by providing additional steps } // Your step can be repeated in case any other step fails, even if your step has already done its job - func (s *HelloWorldStep) Run(operation internal.Operation, log *logrus.Entry) (internal.Operation, time.Duration, error) { + func (s *HelloWorldStep) Run(operation internal.Operation, log *slog.Logger) (internal.Operation, time.Duration, error) { log.Info("Start step") // Check whether your step should be run or if its job has been done in the previous iteration @@ -153,7 +153,7 @@ You can configure SAP BTP, Kyma runtime operations by providing additional steps body := ExternalBodyResponse{} err = json.NewDecoder(response.Body).Decode(&body) if err != nil { - log.Errorf("error: %s", err) + log.Error(fmt.Sprintf("error: %s", err)) // Handle a process failure by returning an error or time.Duration } @@ -163,7 +163,7 @@ You can configure SAP BTP, Kyma runtime operations by providing additional steps operation.HelloWorlds = body.data updatedOperation, err := s.operationStorage.UpdateOperation(operation) if err != nil { - log.Errorf("error: %s", err) + log.Error(fmt.Sprintf("error: %s", err)) // Handle a process failure by returning an error or time.Duration } diff --git a/go.mod b/go.mod index 5e55d14570..6b70ec171b 100644 --- a/go.mod +++ b/go.mod @@ -31,7 +31,6 @@ require ( github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.20.5 github.com/sebdah/goldie/v2 v2.5.5 - github.com/sirupsen/logrus v1.9.3 github.com/stretchr/testify v1.10.0 github.com/vrischmann/envconfig v1.3.0 golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f @@ -104,6 +103,7 @@ require ( github.com/prometheus/procfs v0.15.1 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect github.com/sergi/go-diff v1.3.1 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect github.com/sosodev/duration v1.3.1 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/stretchr/objx v0.5.2 // indirect diff --git a/internal/broker/client.go b/internal/broker/client.go index f3d8dc9b64..d98681a37d 100644 --- a/internal/broker/client.go +++ b/internal/broker/client.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "io" + "log/slog" "net/http" "time" @@ -12,8 +13,6 @@ import ( "github.com/pivotal-cf/brokerapi/v8/domain/apiresponses" "github.com/pkg/errors" "golang.org/x/oauth2/clientcredentials" - - log "github.com/sirupsen/logrus" ) const ( @@ -143,11 +142,11 @@ func (c *Client) Deprovision(instance internal.Instance) (string, error) { } response := serviceInstancesResponseDTO{} - log.Infof("Requesting deprovisioning of the environment with instance id: %q", instance.InstanceID) + slog.Info(fmt.Sprintf("Requesting deprovisioning of the environment with instance id: %q", instance.InstanceID)) err = c.poller.Invoke(func() (bool, error) { err := c.executeRequest(http.MethodDelete, deprovisionURL, http.StatusAccepted, nil, &response) if err != nil { - log.Warn(fmt.Sprintf("while executing request: %s", err.Error())) + slog.Warn(fmt.Sprintf("while executing request: %s", err.Error())) return false, nil } return true, nil @@ -200,13 +199,13 @@ func (c *Client) Unbind(binding internal.Binding) error { return err } - log.Infof("sending unbind request for service binding with ID %q and instance ID: %q", binding.ID, binding.InstanceID) + slog.Info(fmt.Sprintf("sending unbind request for service binding with ID %q and instance ID: %q", binding.ID, binding.InstanceID)) emptyResponse := &apiresponses.EmptyResponse{} for requestAttemptNum := 1; requestAttemptNum <= c.RequestRetries; requestAttemptNum++ { if err = c.executeRequest(http.MethodDelete, unbindURL, http.StatusOK, nil, emptyResponse); err != nil { if errors.Is(err, context.DeadlineExceeded) { - log.Warnf("request failed - timeout (attempt %d/%d)", requestAttemptNum, c.RequestRetries) + slog.Warn(fmt.Sprintf("request failed - timeout (attempt %d/%d)", requestAttemptNum, c.RequestRetries)) continue } break @@ -217,7 +216,7 @@ func (c *Client) Unbind(binding internal.Binding) error { return err } - log.Infof("successfully unbound service binding with ID %q", binding.ID) + slog.Info(fmt.Sprintf("successfully unbound service binding with ID %q", binding.ID)) return nil } @@ -226,22 +225,22 @@ func processResponse(instanceID string, statusCode int, resp *http.Response) (su switch statusCode { case http.StatusAccepted, http.StatusOK: { - log.Infof("Request for instanceID: %s accepted with status: %+v", instanceID, statusCode) + slog.Info(fmt.Sprintf("Request for instanceID: %s accepted with status: %+v", instanceID, statusCode)) operation, err := decodeOperation(resp) if err != nil { return false, err } - log.Infof("For instanceID: %s we received operation: %s", instanceID, operation) + slog.Info(fmt.Sprintf("For instanceID: %s we received operation: %s", instanceID, operation)) return true, nil } case http.StatusUnprocessableEntity: { - log.Warnf("For instanceID: %s we received entity unprocessable - status: %+v", instanceID, statusCode) + slog.Warn(fmt.Sprintf("For instanceID: %s we received entity unprocessable - status: %+v", instanceID, statusCode)) description, errorString, err := decodeErrorResponse(resp) if err != nil { return false, fmt.Errorf("for instanceID: %s: %w", instanceID, err) } - log.Warnf("error: %+v description: %+v instanceID: %s", errorString, description, instanceID) + slog.Warn(fmt.Sprintf("error: %+v description: %+v instanceID: %s", errorString, description, instanceID)) return false, nil } default: @@ -279,7 +278,7 @@ func decodeErrorResponse(resp *http.Response) (string, string, error) { func prepareExpirationRequest(instance internal.Instance, brokerConfigURL string) (*http.Request, error) { expireInstanceUrl := fmt.Sprintf(updateInstanceTmpl, brokerConfigURL, expireInstanceURL, instance.InstanceID) - log.Infof("Requesting expiration of the environment with instanceID: %q", instance.InstanceID) + slog.Info(fmt.Sprintf("Requesting expiration of the environment with instanceID: %q", instance.InstanceID)) request, err := http.NewRequest(http.MethodPut, expireInstanceUrl, nil) if err != nil { @@ -345,7 +344,7 @@ func (c *Client) executeRequest(method, url string, expectedStatus int, requestB func (c *Client) warnOnError(do func() error) { if err := do(); err != nil { - log.Warn(err.Error()) + slog.Warn(err.Error()) } } diff --git a/internal/broker/labeler.go b/internal/broker/labeler.go index 1df9cda298..c866a75f4b 100644 --- a/internal/broker/labeler.go +++ b/internal/broker/labeler.go @@ -4,11 +4,12 @@ import ( "context" "errors" "fmt" + "log/slog" + "os" "strings" "github.com/kyma-project/kyma-environment-broker/internal/customresources" - "github.com/sirupsen/logrus" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" metaerrors "k8s.io/apimachinery/pkg/api/meta" @@ -20,13 +21,15 @@ import ( type Labeler struct { kcpClient client.Client - log logrus.FieldLogger + log *slog.Logger } func NewLabeler(kcpClient client.Client) *Labeler { return &Labeler{ kcpClient: kcpClient, - log: logrus.New(), + log: slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ + Level: slog.LevelInfo, + })), } } @@ -39,7 +42,7 @@ func (l *Labeler) UpdateLabels(id, newGlobalAccountId string) error { } func (l *Labeler) updateCrLabel(id, crName, newGlobalAccountId string) error { - l.log.Infof("update label starting for runtime %s for %s cr with new value %s", id, crName, newGlobalAccountId) + l.log.Info(fmt.Sprintf("update label starting for runtime %s for %s cr with new value %s", id, crName, newGlobalAccountId)) gvk, err := customresources.GvkByName(crName) if err != nil { return fmt.Errorf("while getting gvk for name: %s: %s", crName, err.Error()) @@ -52,7 +55,7 @@ func (l *Labeler) updateCrLabel(id, crName, newGlobalAccountId string) error { return fmt.Errorf("while checking existence of CRD for %s: %s", crName, err.Error()) } if !crdExists { - l.log.Infof("CRD for %s does not exist, skipping", crName) + l.log.Info(fmt.Sprintf("CRD for %s does not exist, skipping", crName)) return nil } @@ -94,10 +97,10 @@ func (l *Labeler) checkCRDExistence(gvk schema.GroupVersionKind) (bool, error) { crd := &apiextensionsv1.CustomResourceDefinition{} if err := l.kcpClient.Get(context.Background(), client.ObjectKey{Name: crdName}, crd); err != nil { if k8serrors.IsNotFound(err) || metaerrors.IsNoMatchError(err) { - l.log.Errorf("CustomResourceDefinition does not exist %s", err.Error()) + l.log.Error(fmt.Sprintf("CustomResourceDefinition does not exist %s", err.Error())) return false, nil } else { - l.log.Errorf("while getting CRD %s: %s", crdName, err.Error()) + l.log.Error(fmt.Sprintf("while getting CRD %s: %s", crdName, err.Error())) return false, err } } diff --git a/internal/httputil/write_response.go b/internal/httputil/write_response.go index 448cc091fe..b1bf56d6a4 100644 --- a/internal/httputil/write_response.go +++ b/internal/httputil/write_response.go @@ -2,9 +2,9 @@ package httputil import ( "encoding/json" + "fmt" + "log/slog" "net/http" - - "github.com/sirupsen/logrus" ) func WriteResponse(w http.ResponseWriter, code int, object interface{}) { @@ -18,7 +18,7 @@ func WriteResponse(w http.ResponseWriter, code int, object interface{}) { w.WriteHeader(code) _, err = w.Write(data) if err != nil { - logrus.Warnf("could not write response %s", string(data)) + slog.Warn(fmt.Sprintf("could not write response %s", string(data))) } } diff --git a/internal/logger/spy_logger.go b/internal/logger/spy_logger.go deleted file mode 100644 index 3733b51c7b..0000000000 --- a/internal/logger/spy_logger.go +++ /dev/null @@ -1,139 +0,0 @@ -// Package copied from https://github.com/kyma-project/kyma/blob/1.11.0/components/service-binding-usage-controller/internal/platform/logger/spy/logger.go -// Only Reset() method was added. -package logger - -import ( - "bufio" - "bytes" - "encoding/json" - "io/ioutil" - "strings" - "testing" - - "github.com/sirupsen/logrus" -) - -// LogSpy is a helper construct for testing logging in unit tests. -// Beware: all methods are working on copies of of original messages buffer and are safe for multiple uses. -type LogSpy struct { - buffer *bytes.Buffer - RawLogger *logrus.Logger - Logger *logrus.Entry -} - -// NewLogSpy is a factory for LogSpy -func NewLogSpy() *LogSpy { - buffer := bytes.NewBuffer([]byte("")) - - rawLgr := &logrus.Logger{ - Out: buffer, - // standard json formatter is used to ease testing - Formatter: new(logrus.JSONFormatter), - Hooks: make(logrus.LevelHooks), - Level: logrus.DebugLevel, - } - - lgr := rawLgr.WithField("testing", true) - - return &LogSpy{ - buffer: buffer, - RawLogger: rawLgr, - Logger: lgr, - } -} - -// AssertErrorLogged checks whatever a specific string was logged as error. -// -// Compared elements: level, message -// -// Wrapped errors are supported as long as original error message ends up in resulting one. -func (s *LogSpy) AssertErrorLogged(t *testing.T, errorExpected error) { - if !s.wasLogged(t, logrus.ErrorLevel, errorExpected.Error()) { - t.Errorf("error was not logged, expected: \"%s\"", errorExpected.Error()) - } -} - -// AssertLogged checks whatever a specific string was logged at a specific level. -// -// Compared elements: level, message -// -// Beware: we are checking for sub-strings and not for the exact match. -func (s *LogSpy) AssertLogged(t *testing.T, level logrus.Level, message string) { - if !s.wasLogged(t, level, message) { - t.Errorf("message was not logged, message: \"%s\", level: %s", message, level) - } -} - -// AssertNotLogged checks whatever a specific string was not logged at a specific level. -// -// Compared elements: level, message -// -// Beware: we are checking for sub-strings and not for the exact match. -func (s *LogSpy) AssertNotLogged(t *testing.T, level logrus.Level, message string) { - if s.wasLogged(t, level, message) { - t.Errorf("message was logged, message: \"%s\", level: %s", message, level) - } -} - -// wasLogged checks whatever a message was logged. -// -// Compared elements: level, message -func (s *LogSpy) wasLogged(t *testing.T, level logrus.Level, message string) bool { - // new reader is created so we are safe for multiple reads - buf := bytes.NewReader(s.buffer.Bytes()) - scanner := bufio.NewScanner(buf) - var entryPartial struct { - Level string `json:"level"` - Msg string `json:"msg"` - } - - for scanner.Scan() { - line := scanner.Text() - - err := json.Unmarshal([]byte(line), &entryPartial) - if err != nil { - t.Fatalf("unexpected error on log line unmarshalling, line: %s", line) - } - - levelMatches := entryPartial.Level == level.String() - - // We are looking only if expected is contained (as opposed to exact match check), - // so that e.g. errors wrapping is supported. - containsMessage := strings.Contains(entryPartial.Msg, message) - - if levelMatches && containsMessage { - return true - } - } - - return false -} - -// DumpAll returns all logged messages. -func (s *LogSpy) DumpAll() []string { - // new reader is created so we are safe for multiple reads - buf := bytes.NewReader(s.buffer.Bytes()) - scanner := bufio.NewScanner(buf) - - out := []string{} - for scanner.Scan() { - out = append(out, scanner.Text()) - } - - return out -} - -// Reset removes logged messages. -func (s *LogSpy) Reset() { - s.buffer.Reset() -} - -// NewLogDummy returns dummy logger which discards logged messages on the fly. -// Useful when logger is required as dependency in unit testing. -func NewLogDummy() *logrus.Entry { - rawLgr := logrus.New() - rawLgr.Out = ioutil.Discard - lgr := rawLgr.WithField("testing", true) - - return lgr -} diff --git a/internal/metricsv2/debuger.go b/internal/metricsv2/debuger.go index 354660f47e..a1f50b8cbe 100644 --- a/internal/metricsv2/debuger.go +++ b/internal/metricsv2/debuger.go @@ -1,17 +1,17 @@ package metricsv2 import ( + "fmt" + "log/slog" "sync" - - "github.com/sirupsen/logrus" ) var ( m sync.Mutex ) -func Debug(logger logrus.FieldLogger, source, message string) { +func Debug(logger *slog.Logger, source, message string) { m.Lock() defer m.Unlock() - logger.Infof("#Debug logs: (%s) : %s", source, message) + logger.Info(fmt.Sprintf("#Debug logs: (%s) : %s", source, message)) } diff --git a/internal/model.go b/internal/model.go index 539684ce98..3552108d61 100644 --- a/internal/model.go +++ b/internal/model.go @@ -2,6 +2,8 @@ package internal import ( "database/sql" + "fmt" + "log/slog" "time" "github.com/kyma-project/kyma-environment-broker/internal/euaccess" @@ -14,7 +16,6 @@ import ( kebError "github.com/kyma-project/kyma-environment-broker/internal/error" "github.com/kyma-project/kyma-environment-broker/internal/events" "github.com/pivotal-cf/brokerapi/v8/domain" - log "github.com/sirupsen/logrus" ) type ProvisionerInputCreator interface { @@ -499,12 +500,12 @@ func NewSuspensionOperationWithID(operationID string, instance *Instance) Deprov func (o *Operation) FinishStage(stageName string) { if stageName == "" { - log.Warnf("Attempt to add empty stage.") + slog.Warn("Attempt to add empty stage.") return } if exists := o.IsStageFinished(stageName); exists { - log.Warnf("Attempt to add stage (%s) which is already saved.", stageName) + slog.Warn(fmt.Sprintf("Attempt to add stage (%s) which is already saved.", stageName)) return } diff --git a/internal/process/deprovisioning/automock/step.go b/internal/process/deprovisioning/automock/step.go index 2dbd8d4a01..c50bd3a68f 100644 --- a/internal/process/deprovisioning/automock/step.go +++ b/internal/process/deprovisioning/automock/step.go @@ -4,7 +4,7 @@ package automock import ( internal "github.com/kyma-project/kyma-environment-broker/internal" - logrus "github.com/sirupsen/logrus" + "log/slog" mock "github.com/stretchr/testify/mock" @@ -31,25 +31,25 @@ func (_m *Step) Name() string { } // Run provides a mock function with given fields: operation, logger -func (_m *Step) Run(operation internal.DeprovisioningOperation, logger logrus.FieldLogger) (internal.DeprovisioningOperation, time.Duration, error) { +func (_m *Step) Run(operation internal.DeprovisioningOperation, logger *slog.Logger) (internal.DeprovisioningOperation, time.Duration, error) { ret := _m.Called(operation, logger) var r0 internal.DeprovisioningOperation - if rf, ok := ret.Get(0).(func(internal.DeprovisioningOperation, logrus.FieldLogger) internal.DeprovisioningOperation); ok { + if rf, ok := ret.Get(0).(func(internal.DeprovisioningOperation, *slog.Logger) internal.DeprovisioningOperation); ok { r0 = rf(operation, logger) } else { r0 = ret.Get(0).(internal.DeprovisioningOperation) } var r1 time.Duration - if rf, ok := ret.Get(1).(func(internal.DeprovisioningOperation, logrus.FieldLogger) time.Duration); ok { + if rf, ok := ret.Get(1).(func(internal.DeprovisioningOperation, *slog.Logger) time.Duration); ok { r1 = rf(operation, logger) } else { r1 = ret.Get(1).(time.Duration) } var r2 error - if rf, ok := ret.Get(2).(func(internal.DeprovisioningOperation, logrus.FieldLogger) error); ok { + if rf, ok := ret.Get(2).(func(internal.DeprovisioningOperation, *slog.Logger) error); ok { r2 = rf(operation, logger) } else { r2 = ret.Error(2) diff --git a/internal/provisioner/graphqlizer.go b/internal/provisioner/graphqlizer.go index 416476314f..2517bc1425 100644 --- a/internal/provisioner/graphqlizer.go +++ b/internal/provisioner/graphqlizer.go @@ -3,11 +3,10 @@ package provisioner import ( "bytes" "encoding/json" + "log/slog" "reflect" "text/template" - "github.com/sirupsen/logrus" - "fmt" "strconv" @@ -332,21 +331,21 @@ func (g *Graphqlizer) marshal(obj interface{}) string { case reflect.Map: s, err := g.genericToGraphQL(obj, `{ {{- range $k, $v := . }}{{ $k }}:{{ marshal $v }},{{ end -}} }`) if err != nil { - logrus.Warnf("failed to marshal labels: %s", err.Error()) + slog.Warn(fmt.Sprintf("failed to marshal labels: %s", err.Error())) return "" } out = s case reflect.Slice, reflect.Array: s, err := g.genericToGraphQL(obj, `[{{ range $i, $e := . }}{{ if $i }},{{ end }}{{ marshal $e }}{{ end }}]`) if err != nil { - logrus.Warnf("failed to marshal labels: %s", err.Error()) + slog.Warn(fmt.Sprintf("failed to marshal labels: %s", err.Error())) return "" } out = s default: marshalled, err := json.Marshal(obj) if err != nil { - logrus.Warnf("failed to marshal labels: %s", err.Error()) + slog.Warn(fmt.Sprintf("failed to marshal labels: %s", err.Error())) return "" } out = string(marshalled) diff --git a/testing/e2e/provisioning/go.mod b/testing/e2e/provisioning/go.mod index baafe1e463..d79daa1e82 100644 --- a/testing/e2e/provisioning/go.mod +++ b/testing/e2e/provisioning/go.mod @@ -8,7 +8,6 @@ require ( github.com/ory/hydra-maester v0.0.27 github.com/pivotal-cf/brokerapi/v7 v7.5.0 github.com/pkg/errors v0.9.1 - github.com/sirupsen/logrus v1.9.3 github.com/stretchr/testify v1.9.0 github.com/thanhpk/randstr v1.0.5 github.com/vrischmann/envconfig v1.3.0 diff --git a/testing/e2e/provisioning/go.sum b/testing/e2e/provisioning/go.sum index 287182a8ee..6174b2eb41 100644 --- a/testing/e2e/provisioning/go.sum +++ b/testing/e2e/provisioning/go.sum @@ -2144,7 +2144,6 @@ github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMB github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= diff --git a/testing/e2e/provisioning/pkg/client/broker/broker_client.go b/testing/e2e/provisioning/pkg/client/broker/broker_client.go index b5b54bd985..646692e9c8 100644 --- a/testing/e2e/provisioning/pkg/client/broker/broker_client.go +++ b/testing/e2e/provisioning/pkg/client/broker/broker_client.go @@ -7,14 +7,15 @@ import ( "fmt" "io" "io/ioutil" + "log/slog" "net/http" + "os" "strings" "time" "github.com/google/uuid" "github.com/pivotal-cf/brokerapi/v7/domain" "github.com/pkg/errors" - "github.com/sirupsen/logrus" "github.com/thanhpk/randstr" "golang.org/x/oauth2/clientcredentials" "k8s.io/apimachinery/pkg/util/wait" @@ -48,10 +49,10 @@ type Client struct { userID string client *http.Client - log logrus.FieldLogger + log *slog.Logger } -func NewClient(ctx context.Context, config Config, globalAccountID, instanceID, subAccountID, userID string, oAuthCfg BrokerOAuthConfig, log logrus.FieldLogger) *Client { +func NewClient(ctx context.Context, config Config, globalAccountID, instanceID, subAccountID, userID string, oAuthCfg BrokerOAuthConfig, log *slog.Logger) *Client { cfg := clientcredentials.Config{ ClientID: oAuthCfg.ClientID, ClientSecret: oAuthCfg.ClientSecret, @@ -108,12 +109,12 @@ type provisionParameters struct { // ProvisionRuntime requests Runtime provisioning in KEB // kymaVersion is optional, if it is empty, the default KEB version will be used func (c *Client) ProvisionRuntime(kymaVersion string) (string, error) { - c.log.Infof("Provisioning Runtime [instanceID: %s, NAME: %s]", c.InstanceID(), c.ClusterName()) + c.log.Info(fmt.Sprintf("Provisioning Runtime [instanceID: %s, NAME: %s]", c.InstanceID(), c.ClusterName())) requestByte, err := c.prepareProvisionDetails(kymaVersion) if err != nil { return "", errors.Wrap(err, "while preparing provision details") } - c.log.Infof("Provisioning parameters: %v", string(requestByte)) + c.log.Info(fmt.Sprintf("Provisioning parameters: %v", string(requestByte))) provisionURL := fmt.Sprintf("%s/service_instances/%s", c.baseURL(), c.InstanceID()) response := provisionResponse{} @@ -132,7 +133,7 @@ func (c *Client) ProvisionRuntime(kymaVersion string) (string, error) { if err != nil { return "", errors.Wrap(err, "while waiting for successful provision call") } - c.log.Infof("Successfully send provision request, got operation ID %s", response.Operation) + c.log.Info(fmt.Sprintf("Successfully send provision request, got operation ID %s", response.Operation)) return response.Operation, nil } @@ -142,7 +143,7 @@ func (c *Client) DeprovisionRuntime() (string, error) { deprovisionURL := fmt.Sprintf(format, c.baseURL(), c.InstanceID(), kymaClassID, c.brokerConfig.PlanID) response := provisionResponse{} - c.log.Infof("Deprovisioning Runtime [ID: %s, NAME: %s]", c.instanceID, c.clusterName) + c.log.Info(fmt.Sprintf("Deprovisioning Runtime [ID: %s, NAME: %s]", c.instanceID, c.clusterName)) err := wait.PollUntilContextTimeout(context.Background(), time.Second, time.Second*5, false, func(ctx context.Context) (bool, error) { err := c.executeRequest(http.MethodDelete, deprovisionURL, http.StatusAccepted, nil, &response) if err != nil { @@ -154,17 +155,17 @@ func (c *Client) DeprovisionRuntime() (string, error) { if err != nil { return "", errors.Wrap(err, "while waiting for successful deprovision call") } - c.log.Infof("Successfully send deprovision request, got operation ID %s", response.Operation) + c.log.Info(fmt.Sprintf("Successfully send deprovision request, got operation ID %s", response.Operation)) return response.Operation, nil } func (c *Client) SuspendRuntime() error { - c.log.Infof("Suspending Runtime [instanceID: %s, NAME: %s]", c.instanceID, c.clusterName) + c.log.Info(fmt.Sprintf("Suspending Runtime [instanceID: %s, NAME: %s]", c.instanceID, c.clusterName)) requestByte, err := c.prepareUpdateDetails(BoolPtr(false)) if err != nil { return errors.Wrap(err, "while preparing update details") } - c.log.Infof("Suspension parameters: %v", string(requestByte)) + c.log.Info(fmt.Sprintf("Suspension parameters: %v", string(requestByte))) format := "%s/service_instances/%s" suspensionURL := fmt.Sprintf(format, c.baseURL(), c.instanceID) @@ -181,17 +182,17 @@ func (c *Client) SuspendRuntime() error { if err != nil { return errors.Wrap(err, "while waiting for successful suspension call") } - c.log.Infof("Successfully send suspension request for %s", suspensionResponse) + c.log.Info(fmt.Sprintf("Successfully send suspension request for %s", suspensionResponse)) return nil } func (c *Client) UnsuspendRuntime() error { - c.log.Infof("Unsuspending Runtime [instanceID: %s, NAME: %s]", c.InstanceID(), c.ClusterName()) + c.log.Info(fmt.Sprintf("Unsuspending Runtime [instanceID: %s, NAME: %s]", c.InstanceID(), c.ClusterName())) requestByte, err := c.prepareUpdateDetails(BoolPtr(true)) if err != nil { return errors.Wrap(err, "while preparing update details") } - c.log.Infof("Unuspension parameters: %v", string(requestByte)) + c.log.Info(fmt.Sprintf("Unsuspension parameters: %v", string(requestByte))) format := "%s/service_instances/%s" suspensionURL := fmt.Sprintf(format, c.baseURL(), c.InstanceID()) @@ -208,7 +209,7 @@ func (c *Client) UnsuspendRuntime() error { if err != nil { return errors.Wrap(err, "while waiting for successful unsuspension call") } - c.log.Infof("Successfully send unsuspension request for %s", unsuspensionResponse) + c.log.Info(fmt.Sprintf("Successfully send unsuspension request for %s", unsuspensionResponse)) return nil } @@ -242,7 +243,7 @@ func (c *Client) AwaitOperationSucceeded(operationID string, timeout time.Durati lastOperationURL = fmt.Sprintf("%s/service_instances/%s/last_operation", c.baseURL(), c.InstanceID()) } - c.log.Infof("Waiting for operation at most %s", timeout.String()) + c.log.Info(fmt.Sprintf("Waiting for operation at most %s", timeout.String())) response := lastOperationResponse{} err := wait.PollUntilContextTimeout(context.Background(), 5*time.Minute, timeout, false, func(ctx context.Context) (bool, error) { @@ -251,10 +252,10 @@ func (c *Client) AwaitOperationSucceeded(operationID string, timeout time.Durati c.log.Warn(errors.Wrap(err, "while executing request").Error()) return false, nil } - c.log.Infof("Last operation status: %s", response.State) + c.log.Info(fmt.Sprintf("Last operation status: %s", response.State)) switch domain.LastOperationState(response.State) { case domain.Succeeded: - c.log.Infof("Operation succeeded!") + c.log.Info("Operation succeeded!") return true, nil case domain.InProgress: return false, nil @@ -263,7 +264,7 @@ func (c *Client) AwaitOperationSucceeded(operationID string, timeout time.Durati return true, errors.New("provisioning failed") default: if response.State == "" { - c.log.Infof("Got empty last operation response") + c.log.Info("Got empty last operation response") return false, nil } return false, nil @@ -295,7 +296,7 @@ func (c *Client) FetchDashboardURL() (string, error) { if err != nil { return "", errors.Wrap(err, "while waiting for dashboardURL") } - c.log.Infof("Successfully fetched dashboard URL: %s", response.DashboardURL) + c.log.Info(fmt.Sprintf("Successfully fetched dashboard URL: %s", response.DashboardURL)) return response.DashboardURL, nil } @@ -385,10 +386,11 @@ func (c *Client) executeRequest(method, url string, expectedStatus int, body io. if resp.StatusCode != expectedStatus { bodyBytes, err := ioutil.ReadAll(resp.Body) if err != nil { - c.log.Fatal(err) + c.log.Error(err.Error()) + os.Exit(1) } bodyString := string(bodyBytes) - c.log.Warnf("%s", bodyString) + c.log.Warn(fmt.Sprintf("%s", bodyString)) return errors.Errorf("got unexpected status code while calling Kyma Environment Broker: want: %d, got: %d (url=%s)", expectedStatus, resp.StatusCode, url) } diff --git a/testing/e2e/provisioning/pkg/client/broker/upgrade_broker_client.go b/testing/e2e/provisioning/pkg/client/broker/upgrade_broker_client.go index 5b3481652c..470f7ef2de 100644 --- a/testing/e2e/provisioning/pkg/client/broker/upgrade_broker_client.go +++ b/testing/e2e/provisioning/pkg/client/broker/upgrade_broker_client.go @@ -7,11 +7,11 @@ import ( "fmt" "io" "io/ioutil" + "log/slog" "net/http" "time" "github.com/pkg/errors" - "github.com/sirupsen/logrus" "golang.org/x/oauth2/clientcredentials" "k8s.io/apimachinery/pkg/util/wait" ) @@ -23,12 +23,12 @@ const ( ) type UpgradeClient struct { - log logrus.FieldLogger + log *slog.Logger URL string client *http.Client } -func NewUpgradeClient(ctx context.Context, oAuthConfig BrokerOAuthConfig, config Config, log logrus.FieldLogger) *UpgradeClient { +func NewUpgradeClient(ctx context.Context, oAuthConfig BrokerOAuthConfig, config Config, log *slog.Logger) *UpgradeClient { cfg := clientcredentials.Config{ ClientID: oAuthConfig.ClientID, ClientSecret: oAuthConfig.ClientSecret, @@ -39,7 +39,7 @@ func NewUpgradeClient(ctx context.Context, oAuthConfig BrokerOAuthConfig, config httpClientOAuth.Timeout = 30 * time.Second return &UpgradeClient{ - log: log.WithField("client", "upgrade_broker_client"), + log: log.With("client", "upgrade_broker_client"), URL: config.URL, client: httpClientOAuth, } @@ -81,7 +81,7 @@ func (c *UpgradeClient) FetchRuntimeID(instanceID string) (string, error) { return true, errors.Wrap(err, "cannot fetch runtimeID") } if err != nil { - c.log.Warnf("runtime is not ready: %s ...", err) + c.log.Warn(fmt.Sprintf("runtime is not ready: %s ...", err)) return false, nil } runtimeID = id @@ -129,7 +129,7 @@ func (c *UpgradeClient) AwaitOperationFinished(orchestrationID string, timeout t return true, errors.Wrap(err, "cannot fetch operation status") } if err != nil { - c.log.Warnf("upgrade is not ready: %s ...", err) + c.log.Warn(fmt.Sprintf("upgrade is not ready: %s ...", err)) return false, nil } return true, nil diff --git a/testing/e2e/provisioning/pkg/client/runtime/runtime_client.go b/testing/e2e/provisioning/pkg/client/runtime/runtime_client.go index d4389e3109..c8aee7e8b3 100644 --- a/testing/e2e/provisioning/pkg/client/runtime/runtime_client.go +++ b/testing/e2e/provisioning/pkg/client/runtime/runtime_client.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io/ioutil" + "log/slog" "net/http" "os" @@ -11,7 +12,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // tenantHeaderName is a header key name for request send by graphQL client @@ -20,14 +20,14 @@ const tenantHeaderName = "tenant" // Client allows to fetch runtime's config and execute the logic against it type Client struct { httpClient http.Client - log logrus.FieldLogger + log *slog.Logger instanceID string tenantID string kcpK8sClient client.Client } -func NewClient(tenantID, instanceID string, clientHttp http.Client, kcpK8sClient client.Client, log logrus.FieldLogger) *Client { +func NewClient(tenantID, instanceID string, clientHttp http.Client, kcpK8sClient client.Client, log *slog.Logger) *Client { return &Client{ tenantID: tenantID, instanceID: instanceID, @@ -95,7 +95,8 @@ func (c *Client) writeConfigToFile(config string) (string, error) { func (c *Client) removeFile(fileName string) { err := os.Remove(fileName) if err != nil { - c.log.Fatal(err) + c.log.Error(err.Error()) + os.Exit(1) } } diff --git a/testing/e2e/provisioning/pkg/client/v1_client/configmap.go b/testing/e2e/provisioning/pkg/client/v1_client/configmap.go index f246c7a73b..d02073c6d3 100644 --- a/testing/e2e/provisioning/pkg/client/v1_client/configmap.go +++ b/testing/e2e/provisioning/pkg/client/v1_client/configmap.go @@ -2,10 +2,11 @@ package v1_client import ( "context" + "fmt" + "log/slog" "time" "github.com/pkg/errors" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" apiErrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/util/wait" @@ -25,10 +26,10 @@ type ConfigMaps interface { type ConfigMapClient struct { client client.Client - log logrus.FieldLogger + log *slog.Logger } -func NewConfigMapClient(client client.Client, log logrus.FieldLogger) *ConfigMapClient { +func NewConfigMapClient(client client.Client, log *slog.Logger) *ConfigMapClient { return &ConfigMapClient{client: client, log: log} } @@ -40,7 +41,7 @@ func (c *ConfigMapClient) Get(name, namespace string) (*v1.ConfigMap, error) { if apiErrors.IsNotFound(err) { return false, err } - c.log.Errorf("while creating config map: %v", err) + c.log.Error(fmt.Sprintf("while creating config map: %v", err)) return false, nil } return true, nil @@ -62,7 +63,7 @@ func (c *ConfigMapClient) Create(configMap v1.ConfigMap) error { } return true, nil } - c.log.Errorf("while creating config map: %v", err) + c.log.Error(fmt.Sprintf("while creating config map: %v", err)) return false, nil } return true, nil @@ -77,7 +78,7 @@ func (c *ConfigMapClient) Update(configMap v1.ConfigMap) error { err := wait.PollUntilContextTimeout(context.Background(), time.Second, timeout, true, func(ctx context.Context) (bool, error) { err := c.client.Update(context.Background(), &configMap) if err != nil { - c.log.Errorf("while updating config map: %v", err) + c.log.Error(fmt.Sprintf("while updating config map: %v", err)) return false, nil } return true, nil @@ -96,7 +97,7 @@ func (c *ConfigMapClient) Delete(configMap v1.ConfigMap) error { c.log.Warn("config map not found") return true, nil } - c.log.Errorf("while deleting config map: %v", err) + c.log.Error(fmt.Sprintf("while deleting config map: %v", err)) return false, nil } return true, nil diff --git a/testing/e2e/provisioning/pkg/client/v1_client/secret.go b/testing/e2e/provisioning/pkg/client/v1_client/secret.go index d309c8e21a..b229610d80 100644 --- a/testing/e2e/provisioning/pkg/client/v1_client/secret.go +++ b/testing/e2e/provisioning/pkg/client/v1_client/secret.go @@ -2,10 +2,11 @@ package v1_client import ( "context" + "fmt" + "log/slog" "time" "github.com/pkg/errors" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" apiErrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/util/wait" @@ -19,10 +20,10 @@ type Secrets interface { type SecretClient struct { client client.Client - log logrus.FieldLogger + log *slog.Logger } -func NewSecretClient(client client.Client, log logrus.FieldLogger) *SecretClient { +func NewSecretClient(client client.Client, log *slog.Logger) *SecretClient { return &SecretClient{client: client, log: log} } @@ -41,7 +42,7 @@ func (c *SecretClient) Create(secret v1.Secret) error { } return true, nil } - c.log.Errorf("while creating secret: %v", err) + c.log.Error(fmt.Sprintf("while creating secret: %v", err)) return false, nil } return true, nil @@ -60,7 +61,7 @@ func (c *SecretClient) Delete(secret v1.Secret) error { c.log.Warn("secret not found") return true, nil } - c.log.Errorf("while creating secret: %v", err) + c.log.Error(fmt.Sprintf("while creating secret: %v", err)) return false, nil } return true, nil diff --git a/testing/e2e/provisioning/test/e2e_provisioning_test.go b/testing/e2e/provisioning/test/e2e_provisioning_test.go index 5d1c3d2e53..f97cb07ae0 100644 --- a/testing/e2e/provisioning/test/e2e_provisioning_test.go +++ b/testing/e2e/provisioning/test/e2e_provisioning_test.go @@ -26,7 +26,7 @@ func Test_E2E_Provisioning(t *testing.T) { operationID, err := ts.brokerClient.ProvisionRuntime("") require.NoError(t, err) - ts.log.Infof("Creating config map %s with test data", ts.ConfigName) + ts.log.Info(fmt.Sprintf("Creating config map %s with test data", ts.ConfigName)) err = ts.configMapClient.Create(configMap) require.NoError(t, err) @@ -36,7 +36,7 @@ func Test_E2E_Provisioning(t *testing.T) { dashboardURL, err := ts.brokerClient.FetchDashboardURL() require.NoError(t, err) - ts.log.Infof("Updating config map %s with dashboardUrl", ts.ConfigName) + ts.log.Info(fmt.Sprintf("Updating config map %s with dashboardUrl", ts.ConfigName)) configMap.Data[dashboardUrlKey] = dashboardURL err = ts.configMapClient.Update(configMap) require.NoError(t, err) @@ -45,7 +45,7 @@ func Test_E2E_Provisioning(t *testing.T) { config, err := ts.runtimeClient.FetchRuntimeConfig() require.NoError(t, err) - ts.log.Infof("Creating a secret %s with test data", ts.ConfigName) + ts.log.Info(fmt.Sprintf("Creating a secret %s with test data", ts.ConfigName)) err = ts.secretClient.Create(ts.testSecret(config)) require.NoError(t, err) diff --git a/testing/e2e/provisioning/test/e2e_suspension_test.go b/testing/e2e/provisioning/test/e2e_suspension_test.go index 861c17dc8d..374d43456b 100644 --- a/testing/e2e/provisioning/test/e2e_suspension_test.go +++ b/testing/e2e/provisioning/test/e2e_suspension_test.go @@ -28,7 +28,7 @@ func Test_E2E_Suspension(t *testing.T) { operationID, err := ts.brokerClient.ProvisionRuntime("") require.NoError(t, err) - ts.log.Infof("Creating config map %s with test data", ts.ConfigName) + ts.log.Info(fmt.Sprintf("Creating config map %s with test data", ts.ConfigName)) err = ts.configMapClient.Create(configMap) require.NoError(t, err) @@ -38,7 +38,7 @@ func Test_E2E_Suspension(t *testing.T) { dashboardURL, err := ts.brokerClient.FetchDashboardURL() require.NoError(t, err) - ts.log.Infof("Updating config map %s with dashboardUrl", ts.ConfigName) + ts.log.Info(fmt.Sprintf("Updating config map %s with dashboardUrl", ts.ConfigName)) configMap.Data[dashboardUrlKey] = dashboardURL err = ts.configMapClient.Update(configMap) require.NoError(t, err) @@ -63,7 +63,7 @@ func Test_E2E_Suspension(t *testing.T) { config, err := ts.runtimeClient.FetchRuntimeConfig() require.NoError(t, err) - ts.log.Infof("Creating a secret %s with test data", ts.ConfigName) + ts.log.Info(fmt.Sprintf("Creating a secret %s with test data", ts.ConfigName)) err = ts.secretClient.Create(ts.testSecret(config)) require.NoError(t, err) diff --git a/testing/e2e/provisioning/test/e2e_upgrade_test.go b/testing/e2e/provisioning/test/e2e_upgrade_test.go index 94e8bcf9e9..f803a3ba97 100644 --- a/testing/e2e/provisioning/test/e2e_upgrade_test.go +++ b/testing/e2e/provisioning/test/e2e_upgrade_test.go @@ -1,6 +1,7 @@ package test import ( + "fmt" "testing" "github.com/stretchr/testify/require" @@ -23,7 +24,7 @@ func Test_E2E_Upgrade(t *testing.T) { operationID, err := ts.brokerClient.ProvisionRuntime(ts.PreUpgradeKymaVersion) require.NoError(t, err) - ts.log.Infof("Creating config map %s with test data", ts.ConfigName) + ts.log.Info(fmt.Sprintf("Creating config map %s with test data", ts.ConfigName)) err = ts.configMapClient.Create(configMap) require.NoError(t, err) @@ -34,7 +35,7 @@ func Test_E2E_Upgrade(t *testing.T) { config, err := ts.runtimeClient.FetchRuntimeConfig() require.NoError(t, err) - ts.log.Infof("Creating a secret %s with test data", ts.ConfigName) + ts.log.Info(fmt.Sprintf("Creating a secret %s with test data", ts.ConfigName)) err = ts.secretClient.Create(ts.testSecret(config)) require.NoError(t, err) } diff --git a/testing/e2e/provisioning/test/test_suite.go b/testing/e2e/provisioning/test/test_suite.go index cdf6c88d2a..4880f3b687 100644 --- a/testing/e2e/provisioning/test/test_suite.go +++ b/testing/e2e/provisioning/test/test_suite.go @@ -3,7 +3,10 @@ package test import ( "context" "crypto/tls" + "fmt" + "log/slog" "net/http" + "os" "testing" "time" @@ -14,7 +17,6 @@ import ( "github.com/kyma-project/kyma-environment-broker/testing/e2e/provisioning/pkg/client/v1_client" "github.com/ory/hydra-maester/api/v1alpha1" "github.com/pkg/errors" - "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/vrischmann/envconfig" @@ -51,7 +53,7 @@ type Suite struct { upgradeSuite *UpgradeSuite - log logrus.FieldLogger + log *slog.Logger brokerClient *broker.Client runtimeClient *runtime.Client secretClient v1_client.Secrets @@ -88,7 +90,9 @@ func newTestSuite(t *testing.T) *Suite { err := envconfig.InitWithPrefix(cfg, "APP") require.NoError(t, err) - log := logrus.New() + log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ + Level: slog.LevelInfo, + })) k8sConfig, err := config.GetConfig() if err != nil { @@ -114,14 +118,14 @@ func newTestSuite(t *testing.T) *Suite { require.NoError(t, err) instanceID = cfgMap.Data[instanceIdKey] - log.Infof("using instance ID %s", instanceID) + log.Info(fmt.Sprintf("using instance ID %s", instanceID)) } httpClient := newHTTPClient(cfg.SkipCertVerification) - brokerClient := broker.NewClient(ctx, cfg.Broker, cfg.TenantID, instanceID, subAccountID, userID, oAuth2Config, log.WithField("service", "broker_client")) + brokerClient := broker.NewClient(ctx, cfg.Broker, cfg.TenantID, instanceID, subAccountID, userID, oAuth2Config, log.With("service", "broker_client")) - runtimeClient := runtime.NewClient(cfg.TenantID, instanceID, *httpClient, cli, log.WithField("service", "runtime_client")) + runtimeClient := runtime.NewClient(cfg.TenantID, instanceID, *httpClient, cli, log.With("service", "runtime_client")) suite := &Suite{ t: t, @@ -167,7 +171,7 @@ func (ts *Suite) Cleanup() { // cleanupResources removes secret and config map used to store data about the test func (ts *Suite) cleanupResources() error { - ts.log.Infof("removing secret %s", ts.ConfigName) + ts.log.Info(fmt.Sprintf("removing secret %s", ts.ConfigName)) err := ts.secretClient.Delete(v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: ts.ConfigName, @@ -178,7 +182,7 @@ func (ts *Suite) cleanupResources() error { return errors.Wrapf(err, "while waiting for secret %s deletion", ts.ConfigName) } - ts.log.Infof("removing config map %s", ts.ConfigName) + ts.log.Info(fmt.Sprintf("removing config map %s", ts.ConfigName)) err = ts.configMapClient.Delete(v1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: ts.ConfigName, diff --git a/testing/e2e/provisioning/test/upgrade_test_suite.go b/testing/e2e/provisioning/test/upgrade_test_suite.go index a03110a1a7..ca539822e7 100644 --- a/testing/e2e/provisioning/test/upgrade_test_suite.go +++ b/testing/e2e/provisioning/test/upgrade_test_suite.go @@ -2,12 +2,12 @@ package test import ( "context" + "log/slog" "testing" "time" "github.com/kyma-project/kyma-environment-broker/testing/e2e/provisioning/pkg/client/broker" - "github.com/sirupsen/logrus" "github.com/stretchr/testify/require" "github.com/vrischmann/envconfig" ) @@ -22,7 +22,7 @@ type UpgradeSuite struct { UpgradeTimeout time.Duration } -func newUpgradeSuite(t *testing.T, ctx context.Context, oAuthConfig broker.BrokerOAuthConfig, config broker.Config, log logrus.FieldLogger) *UpgradeSuite { +func newUpgradeSuite(t *testing.T, ctx context.Context, oAuthConfig broker.BrokerOAuthConfig, config broker.Config, log *slog.Logger) *UpgradeSuite { cfg := &UpgradeConfig{} err := envconfig.InitWithPrefix(cfg, "APP") require.NoError(t, err)