diff --git a/controllers/apim/apidefinition/controller.go b/controllers/apim/apidefinition/controller.go index bcc2a61fa..b2bc68dbb 100644 --- a/controllers/apim/apidefinition/controller.go +++ b/controllers/apim/apidefinition/controller.go @@ -25,6 +25,7 @@ import ( "github.com/gravitee-io/gravitee-kubernetes-operator/internal/errors" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/event" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/k8s" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/template" util "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" @@ -33,7 +34,6 @@ import ( "github.com/gravitee-io/gravitee-kubernetes-operator/controllers/apim/apidefinition/internal" ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/log" ) const requeueAfterTime = time.Second * 5 @@ -53,7 +53,6 @@ func Reconcile( } func reconcileApiTemplate(ctx context.Context, apiDefinition core.ApiDefinitionObject) (ctrl.Result, error) { - logger := log.FromContext(ctx) _, err := util.CreateOrUpdate(ctx, k8s.GetClient(), apiDefinition, func() error { dc, _ := apiDefinition.DeepCopyObject().(core.ApiDefinitionObject) if err := template.Compile(ctx, dc); err != nil { @@ -70,26 +69,26 @@ func reconcileApiTemplate(ctx context.Context, apiDefinition core.ApiDefinitionO }) if err != nil { - logger.Error(err, "Failed to sync API definition template") + log.Error(ctx, err, "Failed to sync API definition template", log.KeyValues(apiDefinition)...) return ctrl.Result{RequeueAfter: requeueAfterTime}, err } - logger.Info("template synced successfully.", "template:", apiDefinition.GetName()) + log.Debug(ctx, "Ingress template synced successfully.", log.KeyValues(apiDefinition)...) if err := internal.UpdateStatusSuccess(ctx, apiDefinition); err != nil { return ctrl.Result{}, err } return ctrl.Result{}, nil } + func reconcileApiDefinition( ctx context.Context, apiDefinition core.ApiDefinitionObject, events *event.Recorder, ) (ctrl.Result, error) { - logger := log.FromContext(ctx) dc, _ := apiDefinition.DeepCopyObject().(core.ApiDefinitionObject) - _, reconcileErr := util.CreateOrUpdate(ctx, k8s.GetClient(), apiDefinition, func() error { + _, err := util.CreateOrUpdate(ctx, k8s.GetClient(), apiDefinition, func() error { util.AddFinalizer(apiDefinition, core.ApiDefinitionFinalizer) k8s.AddAnnotation(apiDefinition, core.LastSpecHashAnnotation, apiDefinition.GetSpec().Hash()) @@ -120,8 +119,8 @@ func reconcileApiDefinition( return ctrl.Result{}, err } - if reconcileErr == nil { - logger.Info("API definition has been reconciled") + if err == nil { + log.InfoEndReconcile(ctx, apiDefinition) return ctrl.Result{}, internal.UpdateStatusSuccess(ctx, apiDefinition) } @@ -129,11 +128,11 @@ func reconcileApiDefinition( return ctrl.Result{}, err } - if errors.IsRecoverable(reconcileErr) { - logger.Error(reconcileErr, "Requeuing reconcile") - return ctrl.Result{RequeueAfter: requeueAfterTime}, reconcileErr + if errors.IsRecoverable(err) { + log.ErrorRequeuingReconcile(ctx, err, apiDefinition) + return ctrl.Result{RequeueAfter: requeueAfterTime}, err } - logger.Error(reconcileErr, "Aborting reconcile") + log.ErrorAbortingReconcile(ctx, err, apiDefinition) return ctrl.Result{}, nil } diff --git a/controllers/apim/apidefinition/internal/api_resources.go b/controllers/apim/apidefinition/internal/api_resources.go index fda307e08..1b4b1a0a9 100644 --- a/controllers/apim/apidefinition/internal/api_resources.go +++ b/controllers/apim/apidefinition/internal/api_resources.go @@ -21,7 +21,6 @@ import ( "github.com/gravitee-io/gravitee-kubernetes-operator/api/v1alpha1" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/k8s" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/template" - "sigs.k8s.io/controller-runtime/pkg/log" ) func resolveResources(ctx context.Context, resources []*base.ResourceOrRef) error { @@ -46,14 +45,6 @@ func resolveIfRef(ctx context.Context, resourceOrRef *base.ResourceOrRef) error namespacedName := resourceOrRef.Ref.NamespacedName() resource := new(v1alpha1.ApiResource) - log.FromContext(ctx).Info( - "Looking for api resource from", - "namespace", - namespacedName.Namespace, - "name", - namespacedName.Name, - ) - if err := k8s.GetClient().Get(ctx, namespacedName, resource); err != nil { return err } diff --git a/controllers/apim/apidefinition/internal/config_map.go b/controllers/apim/apidefinition/internal/config_map.go index 7d3b0ec24..6a233b692 100644 --- a/controllers/apim/apidefinition/internal/config_map.go +++ b/controllers/apim/apidefinition/internal/config_map.go @@ -22,12 +22,12 @@ import ( "github.com/gravitee-io/gravitee-kubernetes-operator/api/v1alpha1" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/core" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/k8s" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/log" ) const ( @@ -47,12 +47,12 @@ func updateConfigMap( ) error { if api.Spec.State == base.StateStopped { if err := deleteConfigMap(ctx, api); err != nil { - log.FromContext(ctx).Error(err, "Unable to delete ConfigMap from API definition") + log.Error(ctx, err, "Unable to delete config map for API definition", log.KeyValues(api)...) return err } } else { if err := saveConfigMap(ctx, api); err != nil { - log.FromContext(ctx).Error(err, "Unable to create or update ConfigMap from API definition") + log.Error(ctx, err, "Unable to create or update config map for API definition", log.KeyValues(api)...) return err } } @@ -126,7 +126,7 @@ func saveConfigMap( err = k8s.GetClient().Get(ctx, lookupKey, currentApiDefinition) if errors.IsNotFound(err) { - log.FromContext(ctx).Info("Creating config map for API.", "name", apiDefinition.GetName()) + log.Debug(ctx, "Creating config map for API", log.KeyValues(apiDefinition)...) return k8s.GetClient().Create(ctx, cm) } @@ -134,13 +134,11 @@ func saveConfigMap( return err } - // Only update the config map if resource version has changed (means api definition has changed). if currentApiDefinition.Data[definitionVersionKey] != apiDefinition.GetResourceVersion() { - log.FromContext(ctx).Info("Updating ConfigMap", "name", apiDefinition.GetName()) + log.Debug(ctx, "Updating config map", log.KeyValues(apiDefinition)...) return k8s.GetClient().Update(ctx, cm) } - log.FromContext(ctx).Info("No change detected on API. Skipped.", "name", apiDefinition.GetName()) return nil } @@ -152,6 +150,6 @@ func deleteConfigMap(ctx context.Context, api client.Object) error { }, } - log.FromContext(ctx).Info("Deleting Config Map associated to API if exists") + log.Debug(ctx, "Deleting any config map associated to the API", log.KeyValues(api)...) return client.IgnoreNotFound(k8s.GetClient().Delete(ctx, configMap)) } diff --git a/controllers/apim/apidefinition/internal/update.go b/controllers/apim/apidefinition/internal/update.go index 6d0e8c185..c321606eb 100644 --- a/controllers/apim/apidefinition/internal/update.go +++ b/controllers/apim/apidefinition/internal/update.go @@ -22,11 +22,11 @@ import ( v4 "github.com/gravitee-io/gravitee-kubernetes-operator/api/model/api/v4" "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/log" "github.com/gravitee-io/gravitee-kubernetes-operator/api/v1alpha1" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/apim" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/errors" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" ) func CreateOrUpdate(ctx context.Context, apiDefinition client.Object) error { @@ -63,7 +63,7 @@ func createOrUpdateV2(ctx context.Context, apiDefinition *v1alpha1.ApiDefinition return nil } - log.FromContext(ctx).Info("Syncing API with APIM") + log.Debug(ctx, "Syncing API definition with control plane", log.KeyValues(apiDefinition)...) apimClient, apimErr := apim.FromContextRef(ctx, spec.Context, apiDefinition.GetNamespace()) if apimErr != nil { @@ -88,6 +88,8 @@ func createOrUpdateV2(ctx context.Context, apiDefinition *v1alpha1.ApiDefinition return err } + log.Debug(ctx, "API successfully synced with control plane", log.KeyValues(apiDefinition)...) + return nil } @@ -97,14 +99,14 @@ func createOrUpdateV4(ctx context.Context, apiDefinition *v1alpha1.ApiV4Definiti spec := &cp.Spec if err := resolveResources(ctx, spec.Resources); err != nil { - log.FromContext(ctx).Error(err, "Unable to resolve API resources from references") + log.Error(ctx, err, "Unable to resolve API resources from references", log.KeyValues(apiDefinition)...) return err } spec.DefinitionContext = v4.NewDefaultKubernetesContext().MergeWith(spec.DefinitionContext) if spec.Context != nil { - log.FromContext(ctx).Info("Syncing API with APIM") + log.Debug(ctx, "Syncing API definition with control plane", log.KeyValues(apiDefinition)...) apimClient, err := apim.FromContextRef(ctx, spec.Context, apiDefinition.GetNamespace()) if err != nil { return err @@ -117,22 +119,22 @@ func createOrUpdateV4(ctx context.Context, apiDefinition *v1alpha1.ApiV4Definiti return err } apiDefinition.Status.Status = *status - log.FromContext(ctx).WithValues("id", spec.ID).Info("API successfully synced with APIM") + log.Debug(ctx, "API successfully synced with control plane", log.KeyValues(apiDefinition)...) } else { cp.PopulateIDs(nil) } if spec.DefinitionContext.SyncFrom == v4.OriginManagement || spec.State == base.StateStopped { - log.FromContext(ctx).Info( - "Deleting config map as API is not managed by operator or is stopped", - "syncFrom", spec.DefinitionContext.SyncFrom, - "state", spec.State, + log.Debug( + ctx, + "Deleting config map as API definition is not synced from the cluster or API is stopped", + log.KeyValues(apiDefinition, "state", spec.State, "synced-from", spec.DefinitionContext.SyncFrom)..., ) if err := deleteConfigMap(ctx, cp); err != nil { return err } } else { - log.FromContext(ctx).Info("Saving config map") + log.Debug(ctx, "Saving config map for API definition", log.KeyValues(apiDefinition)...) if err := saveConfigMap(ctx, cp); err != nil { return err } diff --git a/controllers/apim/apiresource/apiresource_controller.go b/controllers/apim/apiresource/apiresource_controller.go index 67c5be0d3..8ee1dbfcf 100644 --- a/controllers/apim/apiresource/apiresource_controller.go +++ b/controllers/apim/apiresource/apiresource_controller.go @@ -20,6 +20,7 @@ import ( "context" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/k8s" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/template" @@ -33,7 +34,6 @@ import ( "k8s.io/client-go/tools/record" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/log" "github.com/gravitee-io/gravitee-kubernetes-operator/api/v1alpha1" "github.com/gravitee-io/gravitee-kubernetes-operator/controllers/apim/apiresource/internal" @@ -56,7 +56,6 @@ type Reconciler struct { // For more details, check Reconcile and its Result here: // - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.12.2/pkg/reconcile func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) apiResource := &v1alpha1.ApiResource{} if err := r.Get(ctx, req.NamespacedName, apiResource); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) @@ -66,7 +65,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu dc := apiResource.DeepCopy() - _, reconcileErr := util.CreateOrUpdate(ctx, r.Client, apiResource, func() error { + _, err := util.CreateOrUpdate(ctx, r.Client, apiResource, func() error { util.AddFinalizer(apiResource, core.ApiResourceFinalizer) k8s.AddAnnotation(apiResource, core.LastSpecHashAnnotation, hash.Calculate(&apiResource.Spec)) @@ -97,13 +96,13 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu return ctrl.Result{}, err } - if reconcileErr == nil { - logger.Info("API Resource has been reconciled") + if err == nil { + log.InfoEndReconcile(ctx, apiResource) return ctrl.Result{}, nil } // There was an error reconciling the Management Context - return ctrl.Result{}, reconcileErr + return ctrl.Result{}, err } // SetupWithManager sets up the controller with the Manager. diff --git a/controllers/apim/application/application_controller.go b/controllers/apim/application/application_controller.go index 9ff018d01..45cf9aeb8 100644 --- a/controllers/apim/application/application_controller.go +++ b/controllers/apim/application/application_controller.go @@ -26,6 +26,7 @@ import ( "github.com/gravitee-io/gravitee-kubernetes-operator/internal/hash" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/indexer" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/k8s" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/predicate" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/template" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/watch" @@ -40,7 +41,6 @@ import ( "k8s.io/client-go/tools/record" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/log" ) const requeueAfterTime = time.Second * 5 @@ -61,8 +61,6 @@ type Reconciler struct { // +kubebuilder:rbac:groups=gravitee.io,resources=applications/finalizers,verbs=update // +kubebuilder:rbac:groups="",resources=events,verbs=create;patch func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) - application := &v1alpha1.Application{} if err := r.Get(ctx, req.NamespacedName, application); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) @@ -71,13 +69,17 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu events := event.NewRecorder(r.Recorder) if application.Spec.Context == nil { - logger.Error(fmt.Errorf("no context is provided, no attempt will be made to sync with APIM"), "Aborting reconcile") + log.ErrorAbortingReconcile( + ctx, + fmt.Errorf("no context is provided, no attempt will be made to sync with APIM"), + application, + ) return ctrl.Result{}, nil } dc := application.DeepCopy() - _, reconcileErr := util.CreateOrUpdate(ctx, r.Client, application, func() error { + _, err := util.CreateOrUpdate(ctx, r.Client, application, func() error { util.AddFinalizer(application, core.ApplicationFinalizer) k8s.AddAnnotation(application, core.LastSpecHashAnnotation, hash.Calculate(&application.Spec)) @@ -110,8 +112,8 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu application.SetFinalizers(dc.GetFinalizers()) - if reconcileErr == nil { - logger.Info("Application has been reconciled") + if err == nil { + log.InfoEndReconcile(ctx, application) return ctrl.Result{}, internal.UpdateStatusSuccess(ctx, application) } @@ -120,12 +122,12 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu return ctrl.Result{}, err } - if errors.IsRecoverable(reconcileErr) { - logger.Error(reconcileErr, "Requeuing reconcile") - return ctrl.Result{RequeueAfter: requeueAfterTime}, reconcileErr + if errors.IsRecoverable(err) { + log.ErrorRequeuingReconcile(ctx, err, application) + return ctrl.Result{RequeueAfter: requeueAfterTime}, err } - logger.Error(reconcileErr, "Aborting reconcile") + log.ErrorAbortingReconcile(ctx, err, application) return ctrl.Result{}, nil } diff --git a/controllers/apim/ingress/ingress_controller.go b/controllers/apim/ingress/ingress_controller.go index 31c6e209e..24be3af90 100644 --- a/controllers/apim/ingress/ingress_controller.go +++ b/controllers/apim/ingress/ingress_controller.go @@ -22,6 +22,7 @@ import ( util "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/hash" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/env" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/template" @@ -43,7 +44,6 @@ import ( "k8s.io/client-go/tools/record" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/log" ) // Reconciler watches and reconciles Ingress objects. @@ -61,8 +61,6 @@ type Reconciler struct { // Reconcile perform reconciliation logic for Ingress resource that is managed // by the operator. func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) - ingress := &netV1.Ingress{} if err := r.Get(ctx, req.NamespacedName, ingress); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) @@ -72,7 +70,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu dc := ingress.DeepCopy() - _, reconcileErr := util.CreateOrUpdate(ctx, r.Client, ingress, func() error { + _, err := util.CreateOrUpdate(ctx, r.Client, ingress, func() error { util.AddFinalizer(ingress, core.IngressFinalizer) k8s.AddAnnotation(ingress, core.LastSpecHashAnnotation, hash.Calculate(&ingress.Spec)) @@ -100,12 +98,16 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu dc.Status.DeepCopyInto(&ingress.Status) - if reconcileErr != nil { - logger.Error(reconcileErr, "An error occurs while reconciling the Ingress", "Ingress", ingress) - return ctrl.Result{}, reconcileErr + if err != nil { + log.ErrorRequeuingReconcile( + ctx, + err, + ingress, + ) + return ctrl.Result{}, err } - logger.Info("Sync ingress DONE") + log.InfoEndReconcile(ctx, ingress) return ctrl.Result{}, nil } diff --git a/controllers/apim/ingress/internal/api_definition.go b/controllers/apim/ingress/internal/api_definition.go index 53593eb5b..12f6ce7e4 100644 --- a/controllers/apim/ingress/internal/api_definition.go +++ b/controllers/apim/ingress/internal/api_definition.go @@ -18,20 +18,29 @@ import ( "context" "github.com/gravitee-io/gravitee-kubernetes-operator/api/v1alpha1" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/core" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/k8s" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" v1 "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" util "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - "sigs.k8s.io/controller-runtime/pkg/log" ) func createOrUpdateApiDefinition(ctx context.Context, ingress *v1.Ingress) (util.OperationResult, error) { apiDefinition, err := resolveApiDefinitionTemplate(ctx, ingress) if err != nil { - log.FromContext(ctx).Error(err, "ResolveApiDefinition error") + log.Error( + ctx, + err, + "Unable to resolve API definition template", + log.KeyValues( + ingress, + "ingress-template-name", ingress.Annotations[core.IngressTemplateAnnotation], + )..., + ) return util.OperationResultNone, err } @@ -43,7 +52,7 @@ func createOrUpdateApiDefinition(ctx context.Context, ingress *v1.Ingress) (util } if err != nil { - log.FromContext(ctx).Error(err, "unable to create api definition from template") + log.Error(ctx, err, "unable to create api definition from template", log.KeyValues(apiDefinition)...) return util.OperationResultNone, err } @@ -52,10 +61,10 @@ func createOrUpdateApiDefinition(ctx context.Context, ingress *v1.Ingress) (util return updateApiDefinition(ctx, ingress, existingApiDefinition) } - log.FromContext(ctx).Info( - "No change detected on ApiDefinition. Skipped.", - "name", apiDefinition.Name, - "namespace", apiDefinition.Namespace, + log.Debug( + ctx, + "Skipping API definition update for ingress as no changes were detected", + log.KeyValues(ingress)..., ) return util.OperationResultNone, nil } @@ -64,7 +73,15 @@ func createApiDefinition( ctx context.Context, ingress *v1.Ingress, apiDefinition *v1alpha1.ApiDefinition, ) (util.OperationResult, error) { - log.FromContext(ctx).Info("Creating ApiDefinition", "name", apiDefinition.Name, "namespace", apiDefinition.Namespace) + log.Debug( + ctx, + "Creating API definition for ingress", + log.KeyValues( + ingress, + "ingress-api-name", apiDefinition.GetName(), + "ingress-api-namespace", apiDefinition.GetNamespace(), + )..., + ) cli := k8s.GetClient() if err := util.SetOwnerReference(ingress, apiDefinition, cli.Scheme()); err != nil { @@ -78,7 +95,11 @@ func updateApiDefinition( ctx context.Context, ingress *v1.Ingress, apiDefinition *v1alpha1.ApiDefinition, ) (util.OperationResult, error) { - log.FromContext(ctx).Info("Updating ApiDefinition", "name", apiDefinition.Name, "namespace", apiDefinition.Namespace) + log.Debug( + ctx, + "Updating API definition for ingress", + log.KeyValues(ingress)..., + ) cli := k8s.GetClient() err := util.SetOwnerReference(ingress, apiDefinition, cli.Scheme()) if err != nil { diff --git a/controllers/apim/ingress/internal/api_definition_template.go b/controllers/apim/ingress/internal/api_definition_template.go index 4e578e56d..8c7820d50 100644 --- a/controllers/apim/ingress/internal/api_definition_template.go +++ b/controllers/apim/ingress/internal/api_definition_template.go @@ -23,8 +23,8 @@ import ( "github.com/gravitee-io/gravitee-kubernetes-operator/internal/core" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/env" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/k8s" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/log" "github.com/gravitee-io/gravitee-kubernetes-operator/api/model/api/base" v2 "github.com/gravitee-io/gravitee-kubernetes-operator/api/model/api/v2" @@ -51,16 +51,16 @@ func resolveApiDefinitionTemplate( apiDefinition = defaultApiDefinitionTemplate() } - return mapper.New(getMapperOpts(ctx)).Map(apiDefinition, ingress), nil + return mapper.New(getMapperOpts(ctx, ingress)).Map(apiDefinition, ingress), nil } -func getMapperOpts(ctx context.Context) mapper.Opts { +func getMapperOpts(ctx context.Context, ingress *netV1.Ingress) mapper.Opts { opts := mapper.NewOpts() - setNotFoundTemplate(ctx, &opts) + setNotFoundTemplate(ctx, ingress, &opts) return opts } -func setNotFoundTemplate(ctx context.Context, opts *mapper.Opts) { +func setNotFoundTemplate(ctx context.Context, ingress *netV1.Ingress, opts *mapper.Opts) { ns, name := env.Config.CMTemplate404NS, env.Config.CMTemplate404Name if name == "" { @@ -70,12 +70,22 @@ func setNotFoundTemplate(ctx context.Context, opts *mapper.Opts) { cm := coreV1.ConfigMap{} cli := k8s.GetClient() if err := cli.Get(ctx, types.NamespacedName{Namespace: ns, Name: name}, &cm); err != nil { - log.FromContext(ctx).Error(err, "unable to access config map, using default HTTP not found template") + log.Error( + ctx, + err, + "unable to access config map, using default HTTP not found template", + log.KeyValues(ingress)..., + ) return } if err := checkData(cm.Data); err != nil { - log.FromContext(ctx).Error(err, "missing key in config map, using default HTTP not found template") + log.Error( + ctx, + err, + "missing key in config map, using default HTTP not found template", + log.KeyValues(ingress)..., + ) return } diff --git a/controllers/apim/ingress/internal/delete.go b/controllers/apim/ingress/internal/delete.go index 0fa095e02..3be2298a3 100644 --- a/controllers/apim/ingress/internal/delete.go +++ b/controllers/apim/ingress/internal/delete.go @@ -17,15 +17,15 @@ package internal import ( "context" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" v1 "k8s.io/api/networking/v1" - "sigs.k8s.io/controller-runtime/pkg/log" ) func Delete( ctx context.Context, ingress *v1.Ingress) error { if err := deleteIngressTLSReference(ctx, ingress); err != nil { - log.FromContext(ctx).Error(err, "An error occurred while updating the TLS secrets") + log.Error(ctx, err, "An error occurred while updating the TLS secrets", log.KeyValues(ingress)...) return err } diff --git a/controllers/apim/ingress/internal/secret.go b/controllers/apim/ingress/internal/secret.go index 7cfd15008..c40218343 100644 --- a/controllers/apim/ingress/internal/secret.go +++ b/controllers/apim/ingress/internal/secret.go @@ -19,12 +19,12 @@ import ( "crypto/x509" "encoding/json" "encoding/pem" - "errors" "fmt" "strings" "time" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/hash" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/k8s" @@ -36,14 +36,13 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" util "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - "sigs.k8s.io/controller-runtime/pkg/log" ) func updateIngressTLSReference( ctx context.Context, ingress *netV1.Ingress) error { if len(ingress.Spec.TLS) == 0 { - log.FromContext(ctx).Info("no TLS will be configured") + log.Debug(ctx, "Skipping TLS config for ingress", log.KeyValues(ingress)...) return nil } @@ -66,7 +65,7 @@ func updateIngressTLSReference( // If finalizer not present, add it; if !util.ContainsFinalizer(secret, core1.KeyPairFinalizer) { - log.FromContext(ctx).Info("adding finalizer to the tls secret") + log.Debug(ctx, "Adding finalizer to the TLS secret", log.KeyValues(ingress)...) secret.ObjectMeta.Finalizers = append(secret.ObjectMeta.Finalizers, core1.KeyPairFinalizer) k8s.AddAnnotation(secret, core1.LastSpecHashAnnotation, hash.Calculate(&secret.Data)) @@ -94,7 +93,7 @@ func updateIngressTLSReference( values = append(values, fmt.Sprintf("%s/%s", secret.Namespace, secret.Name)) } - log.FromContext(ctx).Info("Update GW PEM registry with the secret names") + log.Debug(ctx, "Updating gateway PEM registry with the secret names", log.KeyValues(ingress)...) return updatePemRegistry(ctx, ingress, key, values) } @@ -124,11 +123,18 @@ func deleteIngressTLSReference( } if hasReferenceToOtherIngress { - log.FromContext(ctx).Error( - errors.New("secret has reference"), - "secret is used by another ingress, it will not be deleted from the keystore") + log.Debug( + ctx, + "secret is used by another ingress, it will not be deleted from the keystore", + log.KeyValues(ingress)..., + ) } else { - log.FromContext(ctx).Info("removing finalizer from secret", "secret", secret.Name) + log.Debug( + ctx, + "removing finalizer from ingress TLS secret", + log.KeyValues(ingress, "secret-name", secret.Name)..., + ) + util.RemoveFinalizer(secret, core1.KeyPairFinalizer) if err = cli.Update(ctx, secret); err != nil { @@ -143,7 +149,7 @@ func deleteIngressTLSReference( return err } - log.FromContext(ctx).Info("gateway pem registry has been successfully updated.") + log.Info(ctx, "gateway pem registry has been successfully updated.") return nil } @@ -156,7 +162,6 @@ func secretHasReference(ctx context.Context, ing *netV1.Ingress, secret *core.Se for i := range il.Items { for _, tls := range il.Items[i].Spec.TLS { if tls.SecretName == secret.Name && il.Items[i].DeletionTimestamp.IsZero() { - log.FromContext(ctx).Info("the secret is already used inside an ingress resource", "resource", il.Items[i].Name) return true, nil } } diff --git a/controllers/apim/ingress/internal/update.go b/controllers/apim/ingress/internal/update.go index ea5b4538e..c2e6b5e9f 100644 --- a/controllers/apim/ingress/internal/update.go +++ b/controllers/apim/ingress/internal/update.go @@ -17,26 +17,32 @@ package internal import ( "context" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" v1 "k8s.io/api/networking/v1" - "sigs.k8s.io/controller-runtime/pkg/log" ) func CreateOrUpdate( ctx context.Context, desired *v1.Ingress) error { if err := updateIngressTLSReference(ctx, desired); err != nil { - log.FromContext(ctx).Error(err, "An error occurred while updating the PEM registry") + log.Error( + ctx, + err, + "An error occurred while updating the gateway PEM registry", + log.KeyValues(desired)..., + ) return err } - operation, apiDefinitionError := createOrUpdateApiDefinition(ctx, desired) - if apiDefinitionError != nil { - log.FromContext(ctx).Error( - apiDefinitionError, - "An error occurs while creating or updating the ApiDefinition", - "Operation", operation, + _, err := createOrUpdateApiDefinition(ctx, desired) + if err != nil { + log.Error( + ctx, + err, + "An error occurs while mapping ingress to an API definition", + log.KeyValues(desired)..., ) - return apiDefinitionError + return err } return nil diff --git a/controllers/apim/managementcontext/managementcontext_controller.go b/controllers/apim/managementcontext/managementcontext_controller.go index 614558ef1..7020ac19b 100644 --- a/controllers/apim/managementcontext/managementcontext_controller.go +++ b/controllers/apim/managementcontext/managementcontext_controller.go @@ -20,6 +20,7 @@ import ( "context" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/k8s" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/template" @@ -33,7 +34,6 @@ import ( "github.com/gravitee-io/gravitee-kubernetes-operator/internal/event" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/watch" "k8s.io/client-go/tools/record" - "sigs.k8s.io/controller-runtime/pkg/log" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" @@ -54,7 +54,6 @@ type Reconciler struct { // +kubebuilder:rbac:groups=gravitee.io,resources=managementcontexts/status,verbs=get;update;patch // +kubebuilder:rbac:groups=gravitee.io,resources=managementcontexts/finalizers,verbs=update func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) managementContext := &v1alpha1.ManagementContext{} if err := r.Get(ctx, req.NamespacedName, managementContext); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) @@ -64,7 +63,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu dc := managementContext.DeepCopy() - _, reconcileErr := util.CreateOrUpdate(ctx, r.Client, managementContext, func() error { + _, err := util.CreateOrUpdate(ctx, r.Client, managementContext, func() error { util.AddFinalizer(managementContext, core.ManagementContextFinalizer) k8s.AddAnnotation(managementContext, core.LastSpecHashAnnotation, hash.Calculate(&managementContext.Spec)) @@ -95,13 +94,13 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu return ctrl.Result{}, err } - if reconcileErr == nil { - logger.Info("Management context has been reconciled") + if err == nil { + log.InfoEndReconcile(ctx, managementContext) return ctrl.Result{}, nil } - // There was an error reconciling the Management Context - return ctrl.Result{}, reconcileErr + log.ErrorAbortingReconcile(ctx, err, managementContext) + return ctrl.Result{}, err } // SetupWithManager sets up the controller with the Manager. diff --git a/controllers/apim/secrets/internal/update.go b/controllers/apim/secrets/internal/update.go index df8ef486d..24b986d51 100644 --- a/controllers/apim/secrets/internal/update.go +++ b/controllers/apim/secrets/internal/update.go @@ -18,13 +18,13 @@ import ( "context" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/k8s" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "github.com/gravitee-io/gravitee-kubernetes-operator/api/v1alpha1" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/core" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/hash" v1 "k8s.io/api/core/v1" util "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - "sigs.k8s.io/controller-runtime/pkg/log" ) func Update(ctx context.Context, secret *v1.Secret) error { @@ -43,7 +43,7 @@ func ensureContextFinalizerAndHash(ctx context.Context, secret *v1.Secret) error } if !util.ContainsFinalizer(secret, core.ManagementContextSecretFinalizer) { - log.FromContext(ctx).Info("secret is used by some management context, adding finalizer") + log.Debug(ctx, "secret is used by some management context, adding finalizer", log.KeyValues(secret)...) util.AddFinalizer(secret, core.ManagementContextSecretFinalizer) } k8s.AddAnnotation(secret, core.LastSpecHashAnnotation, hash.Calculate(&secret.Data)) diff --git a/controllers/apim/secrets/secrets_controller.go b/controllers/apim/secrets/secrets_controller.go index 9b618acf6..fc02ffa22 100644 --- a/controllers/apim/secrets/secrets_controller.go +++ b/controllers/apim/secrets/secrets_controller.go @@ -22,6 +22,7 @@ import ( "github.com/gravitee-io/gravitee-kubernetes-operator/api/v1alpha1" "github.com/gravitee-io/gravitee-kubernetes-operator/controllers/apim/secrets/internal" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/core" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/watch" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" @@ -41,7 +42,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu return ctrl.Result{}, client.IgnoreNotFound(err) } - _, reconcileErr := util.CreateOrUpdate(ctx, r.Client, secret, func() error { + _, err := util.CreateOrUpdate(ctx, r.Client, secret, func() error { if !secret.DeletionTimestamp.IsZero() { if err := internal.Delete(ctx, secret); err != nil { return err @@ -53,11 +54,13 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu return internal.Update(ctx, secret) }) - if reconcileErr == nil { + if err == nil { + log.InfoEndReconcile(ctx, secret) return ctrl.Result{}, nil } - return ctrl.Result{}, reconcileErr + log.ErrorRequeuingReconcile(ctx, err, secret) + return ctrl.Result{}, err } func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { diff --git a/controllers/apim/subscription/subscription_controller.go b/controllers/apim/subscription/subscription_controller.go index f3623a7df..4793b2262 100644 --- a/controllers/apim/subscription/subscription_controller.go +++ b/controllers/apim/subscription/subscription_controller.go @@ -25,11 +25,11 @@ import ( "github.com/gravitee-io/gravitee-kubernetes-operator/internal/event" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/hash" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/k8s" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/template" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" util "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - "sigs.k8s.io/controller-runtime/pkg/log" "github.com/gravitee-io/gravitee-kubernetes-operator/api/v1alpha1" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/predicate" @@ -53,8 +53,6 @@ type Reconciler struct { // +kubebuilder:rbac:groups=gravitee.io,resources=subscriptions/finalizers,verbs=update // +kubebuilder:rbac:groups="",resources=events,verbs=create;patch func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) - subscription := &v1alpha1.Subscription{} if err := r.Get(ctx, req.NamespacedName, subscription); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) @@ -66,7 +64,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu dc := subscription.DeepCopy() - _, reconcileErr := util.CreateOrUpdate(ctx, r.Client, subscription, func() error { + _, err := util.CreateOrUpdate(ctx, r.Client, subscription, func() error { util.AddFinalizer(subscription, core.SubscriptionFinalizer) k8s.AddAnnotation(subscription, core.LastSpecHashAnnotation, hash.Calculate(&subscription.Spec)) @@ -97,8 +95,8 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu return ctrl.Result{}, err } - if reconcileErr == nil { - logger.Info("Subscription has been reconciled") + if err == nil { + log.InfoEndReconcile(ctx, subscription) return ctrl.Result{}, internal.UpdateStatusSuccess(ctx, subscription) } @@ -107,12 +105,12 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu return ctrl.Result{}, err } - if errors.IsRecoverable(reconcileErr) { - logger.Error(reconcileErr, "Requeuing reconcile") - return ctrl.Result{RequeueAfter: requeueAfterTime}, reconcileErr + if errors.IsRecoverable(err) { + log.ErrorRequeuingReconcile(ctx, err, subscription) + return ctrl.Result{RequeueAfter: requeueAfterTime}, err } - logger.Error(reconcileErr, "Aborting reconcile") + log.ErrorAbortingReconcile(ctx, err, subscription) return ctrl.Result{}, nil } diff --git a/helm/gko/README.md b/helm/gko/README.md index 2e430951d..dad770726 100644 --- a/helm/gko/README.md +++ b/helm/gko/README.md @@ -62,6 +62,11 @@ This is where you can configure the deployment itself and the way the operator w | `manager.image.pullPolicy` | Specifies the pullPolicy to use when starting a new container | `IfNotPresent` | | `manager.image.pullSecret` | Specifies the secret holding the credentials used to pull image from the registry | `{}` | | `manager.logs.json` | Whether to output manager logs in JSON format. | `true` | +| `manager.logs.format` | Specifies log output format. Can be either json or console. | `json` | +| `manager.logs.level` | Specifies log level. Can be either debug, info, warn, or error. Wrong values are converted to `info`. | `info` | +| `manager.logs.levelCase` | Specifies the case of the level value. Can be either lower or upper. Wrong values are converted to `lower`. | `lower` | +| `manager.logs.timestamp.field` | Specifies the name of the field to use for the timestamp. | `timestamp` | +| `manager.logs.timestamp.format` | Specifies the format to use for the timestamp. Can be either iso-8601, epoch-second, epoch-millis or epoch-nano. | `epoch-second` | | `manager.configMap.name` | The name of the config map used to set the manager config from this values. | `gko-config` | | `manager.resources.limits.cpu` | The CPU resources limits for the GKO Manager container | `500m` | | `manager.resources.limits.memory` | The memory resources limits for the GKO Manager container | `128Mi` | diff --git a/helm/gko/templates/manager/config.yaml b/helm/gko/templates/manager/config.yaml index 813bef7af..c5a1a5f56 100644 --- a/helm/gko/templates/manager/config.yaml +++ b/helm/gko/templates/manager/config.yaml @@ -35,6 +35,11 @@ data: {{- if not .Values.manager.logs.json }} DEV_MODE: "true" {{- end }} + LOGS_FORMAT: {{ .Values.manager.logs.format }} + LOGS_LEVEL: {{ .Values.manager.logs.level }} + LOGS_LEVEL_CASE: {{ .Values.manager.logs.levelCase }} + LOGS_TIMESTAMP_FIELD: {{ .Values.manager.logs.timestamp.field }} + LOGS_TIMESTAMP_FORMAT: {{ .Values.manager.logs.timestamp.format }} {{- if not .Values.manager.metrics.enabled }} ENABLE_METRICS: "false" {{- end }} diff --git a/helm/gko/values.yaml b/helm/gko/values.yaml index 01a32e1bd..d658c8044 100644 --- a/helm/gko/values.yaml +++ b/helm/gko/values.yaml @@ -62,7 +62,20 @@ manager: pullSecret: {} logs: ## @param manager.logs.json Whether to output manager logs in JSON format. + ## 👎 This value is deprecated in benefit of manager.logs.format json: true + ## @param manager.logs.format Specifies log output format. Can be either json or console. + format: json + ## @param manager.logs.level Specifies log level. Can be either debug, info, warn, or error. Wrong values are converted to `info`. + level: info + ## @param manager.logs.levelCase Specifies the case of the level value. Can be either lower or upper. Wrong values are converted to `lower`. + levelCase: lower + timestamp: + ## @param manager.logs.timestamp.field Specifies the name of the field to use for the timestamp. + field: timestamp + ## @param manager.logs.timestamp.format Specifies the format to use for the timestamp. Can be either iso-8601, epoch-second, epoch-millis or epoch-nano. + ## Wrong values are converted to `iso-8601`. + format: epoch-second configMap: ## @param manager.configMap.name The name of the config map used to set the manager config from this values. name: gko-config diff --git a/internal/env/env.go b/internal/env/env.go index 73893afe7..8aec4bb48 100644 --- a/internal/env/env.go +++ b/internal/env/env.go @@ -39,6 +39,11 @@ const ( TrueString = "true" IngressClasses = "INGRESS_CLASSES" CheckApiContextPathConflictInCluster = "CHECK_API_CONTEXT_PATH_CONFLICT_IN_CLUSTER" + LogsFormat = "LOGS_FORMAT" + LogsLevel = "LOGS_LEVEL" + LogsTimestampCase = "LOGS_LEVEL_CASE" + LogsTimestampField = "LOGS_TIMESTAMP_FIELD" + LogsTimestampFormat = "LOGS_TIMESTAMP_FORMAT" // This default are applied when running the app locally. defaultWebhookPort = 9443 @@ -61,6 +66,11 @@ var Config = struct { HTTPClientTimeoutSeconds int IngressClasses []string CheckApiContextPathConflictInCluster bool + LogsFormat string + LogsLevel string + LogsLevelCase string + LogsTimestampField string + LogsTimestampFormat string }{} func init() { @@ -83,6 +93,10 @@ func init() { ingressClass = os.Getenv(IngressClasses) } Config.IngressClasses = strings.Split(ingressClass, ",") + Config.LogsFormat = os.Getenv(LogsFormat) + Config.LogsLevel = os.Getenv(LogsLevel) + Config.LogsTimestampField = os.Getenv(LogsTimestampField) + Config.LogsTimestampFormat = os.Getenv(LogsTimestampFormat) } func parseInt(key string, defaultValue int) int { diff --git a/internal/log/log.go b/internal/log/log.go new file mode 100644 index 000000000..a4e315922 --- /dev/null +++ b/internal/log/log.go @@ -0,0 +1,204 @@ +// Copyright (C) 2015 The Gravitee team (http://gravitee.io) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package log + +import ( + "context" + "fmt" + + "github.com/go-logr/zapr" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/core" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/env" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + kLog "k8s.io/klog/v2" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/log" +) + +var sink *zap.Logger + +type raw struct { + sink *zap.Logger +} + +var Global raw + +func (w raw) Debug(message string) { + w.sink.Debug(message) +} + +func (w raw) Info(message string) { + w.sink.Info(message) +} + +func (w raw) Infof(message string, args ...any) { + w.sink.Info(fmt.Sprintf(message, args...)) +} + +func (w raw) Debugf(message string, args ...any) { + w.sink.Debug(fmt.Sprintf(message, args...)) +} + +func (w raw) Warn(message string) { + w.sink.Warn(message) +} + +func (w raw) Error(err error, message string) { + w.sink.Error(message, zap.Error(err)) +} + +func (w raw) Errorf(err error, message string, args ...any) { + w.sink.Error(fmt.Sprintf(message, args...), zap.Error(err)) +} + +func Debug(ctx context.Context, message string, keysAndValues ...any) { + log.FromContext(ctx).V(1).Info(message, keysAndValues...) +} + +func Info(ctx context.Context, message string, keysAndValues ...any) { + log.FromContext(ctx).Info(message, keysAndValues...) +} + +func Error(ctx context.Context, err error, message string, keysAndValues ...any) { + log.FromContext(ctx).Error(err, message, keysAndValues...) +} + +func InfoInitReconcile(ctx context.Context, obj client.Object) { + log.FromContext(ctx).Info( + fmt.Sprintf( + "Reconciling resource [%s]", + obj.GetObjectKind().GroupVersionKind().GroupKind(), + ), + KeyValues(obj)..., + ) +} + +func InfoEndReconcile(ctx context.Context, obj client.Object) { + log.FromContext(ctx).Info( + fmt.Sprintf( + "Resource [%s] as been successfully reconciled", + obj.GetObjectKind().GroupVersionKind().GroupKind(), + ), + KeyValues(obj)..., + ) +} + +func ErrorRequeuingReconcile(ctx context.Context, err error, obj client.Object) { + log.FromContext(ctx).Error( + err, + fmt.Sprintf( + "Requeuing reconcile of resource [%s] due to an error", + obj.GetObjectKind().GroupVersionKind().GroupKind(), + ), + KeyValues(obj)..., + ) +} + +func ErrorAbortingReconcile(ctx context.Context, err error, obj client.Object) { + log.FromContext(ctx).Error( + err, + fmt.Sprintf( + "Aborting reconcile of resource [%s] due to an unrecoverable error", + obj.GetObjectKind(), + ), + KeyValues(obj)..., + ) +} + +func KeyValues(obj client.Object, keyValues ...any) []any { + props := []any{} + if cta, ok := obj.(core.ContextAwareObject); ok { + props = append(props, "resource-id") + props = append(props, cta.GetID()) + props = append(props, "management-context-name") + props = append(props, cta.ContextRef().GetName()) + props = append(props, "management-context-namespace") + props = append(props, cta.ContextRef().GetNamespace()) + props = append(props, "environment-id") + props = append(props, cta.GetEnvID()) + props = append(props, "organization-id") + props = append(props, cta.GetOrgID()) + } + props = append(props, keyValues...) + return props +} + +func init() { + config := zap.Config{ + Level: getLogLevel(), + Encoding: getEncoding(), + EncoderConfig: setUpEncoderConfig(), + OutputPaths: []string{"stdout"}, + } + sink = zap.Must(config.Build()) + logger := zapr.NewLogger(sink) + ctrl.SetLogger(logger) + log.SetLogger(logger) + kLog.SetLogger(logger) + Global = raw{sink: sink} +} + +func getEncoding() string { + if env.Config.LogsFormat != "json" { + return "console" + } + return "json" +} + +func setUpEncoderConfig() zapcore.EncoderConfig { + config := zap.NewProductionEncoderConfig() + config.MessageKey = "message" + config.TimeKey = env.Config.LogsTimestampField + config.LevelKey = "level" + config.NameKey = "logger" + config.CallerKey = "" + config.StacktraceKey = "stacktrace" + config.LineEnding = zapcore.DefaultLineEnding + config.EncodeLevel = getLevelCase() + config.EncodeTime = getTimeEncoder() + return config +} + +func getLevelCase() zapcore.LevelEncoder { + if env.Config.LogsLevelCase == "lower" { + return zapcore.LowercaseLevelEncoder + } + return zapcore.CapitalLevelEncoder +} + +func getLogLevel() zap.AtomicLevel { + level, err := zapcore.ParseLevel(env.Config.LogsLevel) + if err != nil { + return zap.NewAtomicLevelAt(zap.InfoLevel) + } + return zap.NewAtomicLevelAt(level) +} + +func getTimeEncoder() zapcore.TimeEncoder { + switch env.Config.LogsTimestampFormat { + case "epoch-second": + return zapcore.EpochTimeEncoder + case "epoch-millis": + return zapcore.EpochMillisTimeEncoder + case "epoch-nano": + return zapcore.EpochNanosTimeEncoder + case "iso-8601": + return zapcore.ISO8601TimeEncoder + default: + return zapcore.ISO8601TimeEncoder + } +} diff --git a/internal/logging/logging.go b/internal/logging/logging.go deleted file mode 100644 index ea54e6395..000000000 --- a/internal/logging/logging.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (C) 2015 The Gravitee team (http://gravitee.io) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logging - -import ( - "go.uber.org/zap/zapcore" - "sigs.k8s.io/controller-runtime/pkg/log/zap" -) - -func NewEncoderConfigOption() []zap.EncoderConfigOption { - return []zap.EncoderConfigOption{ - func(config *zapcore.EncoderConfig) { - config.MessageKey = "message" - config.TimeKey = "timestamp" - config.LevelKey = "level" - config.NameKey = "logger" - config.CallerKey = "caller" - config.FunctionKey = zapcore.OmitKey - config.StacktraceKey = "stacktrace" - config.LineEnding = zapcore.DefaultLineEnding - config.EncodeLevel = zapcore.LowercaseLevelEncoder - config.EncodeTime = zapcore.EpochTimeEncoder - config.EncodeDuration = zapcore.SecondsDurationEncoder - config.EncodeCaller = zapcore.ShortCallerEncoder - }, - } -} diff --git a/internal/watch/watch.go b/internal/watch/watch.go index 67b120de1..2b0ca06f3 100644 --- a/internal/watch/watch.go +++ b/internal/watch/watch.go @@ -16,12 +16,13 @@ package watch import ( "context" + "errors" "fmt" - "reflect" "github.com/gravitee-io/gravitee-kubernetes-operator/api/model/refs" "github.com/gravitee-io/gravitee-kubernetes-operator/api/v1alpha1" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/indexer" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/search" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/types/list" "k8s.io/apimachinery/pkg/api/meta" @@ -30,7 +31,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/reconcile" ) @@ -158,27 +158,38 @@ func (w *Type) queueByFieldReferencing( q workqueue.TypedRateLimitingInterface[reconcile.Request], ) { objectList, err := list.OfType(w.objectList) + queueKind := w.objectList.GetObjectKind().GroupVersionKind().Kind if err != nil { - log.FromContext(w.ctx).Error(err, "unable to create list of type", "type", w.objectList) + log.Error(w.ctx, err, fmt.Sprintf("Unable to create list from kind [%s]", queueKind)) return } - if sErr := search.FindByFieldReferencing(w.ctx, field, ref, objectList); sErr != nil { - log.FromContext(w.ctx).Error(sErr, "error while searching for items referencing", "reference", ref.String()) + if err := search.FindByFieldReferencing(w.ctx, field, ref, objectList); err != nil { + log.Error( + w.ctx, + err, + fmt.Sprintf("Error while searching for items referencing [%s]", ref), + ) return } items, err := meta.ExtractList(objectList) if err != nil { - log.FromContext(w.ctx).Error(err, "error while extracting list items of type", "type", w.objectList) + log.Error( + w.ctx, + err, + fmt.Sprintf("Error while extracting list items of kind [%s]", queueKind), + ) } for i := range items { if item, ok := items[i].(client.Object); !ok { - log.FromContext(w.ctx).Error( - fmt.Errorf("unable to convert the item to client.Object type"), - "type", reflect.TypeOf(items[i])) + log.Error( + w.ctx, + errors.New("unsupported type"), + "List item is not a client object and cannot be added to the queue", + ) } else { q.Add(reconcile.Request{NamespacedName: types.NamespacedName{ Name: item.GetName(), diff --git a/internal/webhook/certs.go b/internal/webhook/certs.go index 89dac833e..e0d70f00a 100644 --- a/internal/webhook/certs.go +++ b/internal/webhook/certs.go @@ -21,18 +21,17 @@ import ( "crypto/x509" "crypto/x509/pkix" "encoding/pem" - "fmt" "math/big" "net" "strings" "time" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "golang.org/x/net/context" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/log" ) const ( @@ -51,7 +50,6 @@ func NewWebhookPatcher() *Patcher { conf := ctrl.GetConfigOrDie() cli, err := kubernetes.NewForConfig(conf) if err != nil { - log.FromContext(context.Background()).Error(err, "unable to create Kubernetes client") panic(err) } @@ -63,11 +61,11 @@ func NewWebhookPatcher() *Patcher { func (p *Patcher) CreateSecret(ctx context.Context, secretName, namespace, host string) error { ca := p.getCaFromSecret(ctx, secretName, namespace) if ca == nil { - log.FromContext(ctx).Info("creating new CA secret for GKO webhook") + log.Global.Info("Creating a new CA secret for further usage by admission webhook") newCa, newCert, newKey := GenerateCerts(ctx, host) return p.saveCertsToSecret(ctx, secretName, namespace, CertName, KeyName, newCa, newCert, newKey) } else { - log.FromContext(ctx).Info("Webhook secret already exists, no change will be applied") + log.Global.Infof("Found CA secret [%s] matching admission webhook configuration", secretName) } return nil @@ -78,10 +76,10 @@ func (p *Patcher) UpdateValidationCaBundle(ctx context.Context, webhookName, sec ValidatingWebhookConfigurations().Get(ctx, webhookName, metav1.GetOptions{}) if errors.IsNotFound(err) { - log.FromContext(ctx).Error(err, "GKO validating webhook configuration doesn't exit.") + log.Global.Error(err, "Validating webhook configuration could not be found") return err } else if err != nil { - log.FromContext(ctx).Error(err, "unable to get validating webhook") + log.Global.Error(err, "Unable to get validating webhook") return err } @@ -92,7 +90,7 @@ func (p *Patcher) UpdateValidationCaBundle(ctx context.Context, webhookName, sec _, err = p.client.AdmissionregistrationV1(). ValidatingWebhookConfigurations().Update(ctx, webhookConfig, metav1.UpdateOptions{}) if err != nil { - log.FromContext(ctx).Error(err, "can't update GKO validating webhook configuration") + log.Global.Error(err, "Cannot update validating webhook configuration") return err } @@ -104,10 +102,10 @@ func (p *Patcher) UpdateMutationCaBundle(ctx context.Context, webhookName, secre MutatingWebhookConfigurations().Get(ctx, webhookName, metav1.GetOptions{}) if errors.IsNotFound(err) { - log.FromContext(ctx).Error(err, "GKO mutating webhook configuration doesn't exit.") + log.Global.Error(err, "Mutating webhook configuration could not be found") return err } else if err != nil { - log.FromContext(ctx).Error(err, "unable to get mutating webhook") + log.Global.Error(err, "Unable to get mutating webhook") return err } @@ -118,7 +116,7 @@ func (p *Patcher) UpdateMutationCaBundle(ctx context.Context, webhookName, secre _, err = p.client.AdmissionregistrationV1(). MutatingWebhookConfigurations().Update(ctx, webhookConfig, metav1.UpdateOptions{}) if err != nil { - log.FromContext(ctx).Error(err, "can't update GKO mutating webhook configuration") + log.Global.Error(err, "Cannot update mutating webhook configuration") return err } @@ -128,11 +126,11 @@ func (p *Patcher) UpdateMutationCaBundle(ctx context.Context, webhookName, secre // getCaFromSecret will check for the presence of a secret. If it exists, will return the content of the // "ca" from the secret, otherwise will return nil. func (p *Patcher) getCaFromSecret(ctx context.Context, secretName string, namespace string) []byte { - log.FromContext(ctx).Info(fmt.Sprintf("getting secret '%s' in namespace '%s'", secretName, namespace)) + log.Global.Debugf("Getting secret [%s] in namespace [%s]", secretName, namespace) secret, err := p.client.CoreV1().Secrets(namespace).Get(ctx, secretName, metav1.GetOptions{}) if err != nil { - log.FromContext(ctx).Error(err, "error getting GKO webhook CA secret") + log.Global.Error(err, "Could not get admission webhook CA secret") panic(err) } @@ -142,7 +140,7 @@ func (p *Patcher) getCaFromSecret(ctx context.Context, secretName string, namesp // SaveCertsToSecret saves the provided ca, cert and key into a secret in the specified namespace. func (p *Patcher) saveCertsToSecret(ctx context.Context, secretName, namespace, certName, keyName string, ca, cert, key []byte) error { - log.FromContext(ctx).Info("saving to webhook secret '%s' in namespace '%s'", secretName, namespace) + log.Global.Debugf("Saving to webhook secret '%s' in namespace '%s'", secretName, namespace) secret, err := p.client.CoreV1().Secrets(namespace).Get(ctx, secretName, metav1.GetOptions{}) if err != nil { @@ -166,11 +164,11 @@ func GenerateCerts(ctx context.Context, host string) ([]byte, []byte, []byte) { serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) //nolint:gomnd // LSH number serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { - log.FromContext(ctx).Error(err, "failed to generate serial number") + log.Global.Error(err, "Failed to generate admission webhook serial number") } rootKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { - log.FromContext(ctx).Error(err, "failed scdsa.GenerateKey") + log.Global.Error(err, "Failed to generate admission webhook key") } rootTemplate := x509.Certificate{ @@ -186,21 +184,21 @@ func GenerateCerts(ctx context.Context, host string) ([]byte, []byte, []byte) { derBytes, err := x509.CreateCertificate(rand.Reader, &rootTemplate, &rootTemplate, &rootKey.PublicKey, rootKey) if err != nil { - log.FromContext(ctx).Error(err, "failed createCertificate for Ca") + log.Global.Error(err, "Failed to create CA certificate for admission webhook") } ca := encodeCert(derBytes) leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { - log.FromContext(ctx).Error(err, "failed createLeafKey for certificate") + log.Global.Error(err, "Failed to create leaf key for admission webhook certificate") } - key := encodeKey(ctx, leafKey) + key := encodeKey(leafKey) serialNumber, err = rand.Int(rand.Reader, serialNumberLimit) if err != nil { - log.FromContext(ctx).Error(err, "failed to generate serial number") + log.Global.Error(err, "Failed to generate serial number for admission webhook certificate") } leafTemplate := x509.Certificate{ SerialNumber: serialNumber, @@ -223,17 +221,17 @@ func GenerateCerts(ctx context.Context, host string) ([]byte, []byte, []byte) { derBytes, err = x509.CreateCertificate(rand.Reader, &leafTemplate, &rootTemplate, &leafKey.PublicKey, rootKey) if err != nil { - log.FromContext(ctx).Error(err, "failed createLeaf certificate") + log.Global.Error(err, "Failed to create leaf certificate for admission webhook") } cert := encodeCert(derBytes) return ca, cert, key } -func encodeKey(ctx context.Context, key *ecdsa.PrivateKey) []byte { +func encodeKey(key *ecdsa.PrivateKey) []byte { b, err := x509.MarshalECPrivateKey(key) if err != nil { - log.FromContext(ctx).Error(err, "unable to marshal ECDSA private key") + log.Global.Error(err, "Unable to marshal ECDSA private key for admission webhook") } return pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: b}) } diff --git a/main.go b/main.go index a384a8060..88d05c3bc 100644 --- a/main.go +++ b/main.go @@ -32,6 +32,7 @@ import ( mctxAdmission "github.com/gravitee-io/gravitee-kubernetes-operator/internal/admission/mctx" resourceAdmission "github.com/gravitee-io/gravitee-kubernetes-operator/internal/admission/resource" subAdmission "github.com/gravitee-io/gravitee-kubernetes-operator/internal/admission/subscription" + "github.com/gravitee-io/gravitee-kubernetes-operator/internal/log" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/k8s" wk "github.com/gravitee-io/gravitee-kubernetes-operator/internal/webhook" @@ -50,7 +51,6 @@ import ( v1 "k8s.io/api/networking/v1" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/indexer" - "github.com/gravitee-io/gravitee-kubernetes-operator/internal/logging" "github.com/gravitee-io/gravitee-kubernetes-operator/internal/watch" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) @@ -69,14 +69,12 @@ import ( clientgoscheme "k8s.io/client-go/kubernetes/scheme" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/healthz" - "sigs.k8s.io/controller-runtime/pkg/log/zap" metricServer "sigs.k8s.io/controller-runtime/pkg/metrics/server" //+kubebuilder:scaffold:imports ) var ( - scheme = runtime.NewScheme() - setupLog = ctrl.Log.WithName("setup") + scheme = runtime.NewScheme() //go:embed helm helm embed.FS @@ -113,23 +111,14 @@ func main() { }) } - opts := zap.Options{ - Development: env.Config.Development, - EncoderConfigOptions: logging.NewEncoderConfigOption(), - } - - opts.BindFlags(flag.CommandLine) - flag.Parse() - ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) - if !env.Config.EnableMetrics { metricsAddr = "0" // disables metrics } if env.Config.HTTPClientInsecureSkipVerify { - setupLog.Info("TLS verification is skipped for APIM HTTP client") + log.Global.Warn("TLS certificates verification is skipped for APIM HTTP client") } metrics := metricServer.Options{BindAddress: metricsAddr} @@ -147,19 +136,19 @@ func main() { k8s.RegisterClient(mgr.GetClient()) if err != nil { - setupLog.Error(err, "unable to start manager") + log.Global.Error(err, "Unable to start manager") os.Exit(1) } if env.Config.ApplyCRDs { if err = applyCRDs(); err != nil { - setupLog.Error(err, "unable to apply custom resource definitions") + log.Global.Error(err, "Unable to apply custom resource definitions") os.Exit(1) } } if err = indexer.InitCache(context.Background(), mgr.GetCache()); err != nil { - setupLog.Error(err, "unable to start manager") + log.Global.Error(err, "Unable to start manager") os.Exit(1) } @@ -168,7 +157,7 @@ func main() { if env.Config.EnableWebhook { err = setupAdmissionWebhooks(mgr) if err != nil { - setupLog.Error(err, "unable to start manager") + log.Global.Error(err, "Unable to start manager") os.Exit(1) } } @@ -176,18 +165,18 @@ func main() { //+kubebuilder:scaffold:builder if healthCheckErr := mgr.AddHealthzCheck("healthz", healthz.Ping); healthCheckErr != nil { - setupLog.Error(healthCheckErr, "unable to set up health check") + log.Global.Error(healthCheckErr, "Unable to set up health check") os.Exit(1) } if readyCheckErr := mgr.AddReadyzCheck("readyz", healthz.Ping); readyCheckErr != nil { - setupLog.Error(readyCheckErr, "unable to set up ready check") + log.Global.Error(readyCheckErr, "Unable to set up ready check") os.Exit(1) } - setupLog.Info("starting manager") - if startErr := mgr.Start(ctrl.SetupSignalHandler()); startErr != nil { - setupLog.Error(startErr, "problem running manager") + log.Global.Info("Starting manager") + if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { + log.Global.Error(err, "Unable to start manager") os.Exit(1) } } @@ -204,15 +193,13 @@ func buildCacheOptions(ns string) cache.Options { } func registerControllers(mgr manager.Manager) { - const msg = "unable to create controller" - const controller = "controller" if err := (&apidefinition.Reconciler{ Client: k8s.GetClient(), Scheme: mgr.GetScheme(), Recorder: mgr.GetEventRecorderFor("apidefinitionv2-controller"), Watcher: watch.New(context.Background(), k8s.GetClient(), &v1alpha1.ApiDefinitionList{}), }).SetupWithManager(mgr); err != nil { - setupLog.Error(err, msg, controller, "ApiDefinition") + log.Global.Error(err, "Unable to create controller for API definitions") os.Exit(1) } @@ -222,7 +209,7 @@ func registerControllers(mgr manager.Manager) { Recorder: mgr.GetEventRecorderFor("apiv4definition-controller"), Watcher: watch.New(context.Background(), k8s.GetClient(), &v1alpha1.ApiV4DefinitionList{}), }).SetupWithManager(mgr); err != nil { - setupLog.Error(err, msg, controller, "ApiV4Definition") + log.Global.Error(err, "Unable to create controller for API v4 definitions") os.Exit(1) } @@ -232,7 +219,7 @@ func registerControllers(mgr manager.Manager) { Recorder: mgr.GetEventRecorderFor("managementcontext-controller"), Watcher: watch.New(context.Background(), k8s.GetClient(), &v1alpha1.ManagementContextList{}), }).SetupWithManager(mgr); err != nil { - setupLog.Error(err, msg, controller, "ManagementContext") + log.Global.Error(err, "Unable to create controller for management contexts") os.Exit(1) } if err := (&ingress.Reconciler{ @@ -241,7 +228,7 @@ func registerControllers(mgr manager.Manager) { Recorder: mgr.GetEventRecorderFor("ingress-controller"), Watcher: watch.New(context.Background(), k8s.GetClient(), &v1.IngressList{}), }).SetupWithManager(mgr); err != nil { - setupLog.Error(err, msg, controller, "Ingress") + log.Global.Error(err, "Unable to create controller for ingresses") os.Exit(1) } if err := (&apiresource.Reconciler{ @@ -249,7 +236,7 @@ func registerControllers(mgr manager.Manager) { Scheme: mgr.GetScheme(), Recorder: mgr.GetEventRecorderFor("apiresource-controller"), }).SetupWithManager(mgr); err != nil { - setupLog.Error(err, msg, controller, "ApiResource") + log.Global.Error(err, "Unable to create controller for API resources") os.Exit(1) } if err := (&application.Reconciler{ @@ -258,7 +245,7 @@ func registerControllers(mgr manager.Manager) { Recorder: mgr.GetEventRecorderFor("application-controller"), Watcher: watch.New(context.Background(), k8s.GetClient(), &v1alpha1.ApplicationList{}), }).SetupWithManager(mgr); err != nil { - setupLog.Error(err, msg, controller, "Application") + log.Global.Error(err, "Unable to create controller for applications") os.Exit(1) } @@ -267,7 +254,7 @@ func registerControllers(mgr manager.Manager) { Client: mgr.GetClient(), Recorder: mgr.GetEventRecorderFor("subscription-controller"), }).SetupWithManager(mgr); err != nil { - setupLog.Error(err, msg, controller, "Subscription") + log.Global.Error(err, "Unable to create controller for subscriptions") os.Exit(1) } @@ -275,7 +262,7 @@ func registerControllers(mgr manager.Manager) { Client: k8s.GetClient(), Scheme: mgr.GetScheme(), }).SetupWithManager(mgr); err != nil { - setupLog.Error(err, msg, controller, "Secret") + log.Global.Error(err, "Unable to create controller for secrets") os.Exit(1) } } @@ -313,7 +300,7 @@ func applyCRDs() error { crd := &unstructured.Unstructured{Object: obj} if crd, err = client.Resource(version).Apply(ctx, crd.GetName(), crd, opts); err == nil { - setupLog.Info("applied resource definition", "name", crd.GetName()) + log.Global.Infof("Applied resource definition [%s]", crd) } return err @@ -321,7 +308,7 @@ func applyCRDs() error { } func patchAdmissionWebhook() { - setupLog.Info("setting up Admission Webhook Server") + log.Global.Debug("Setting up Admission Webhook Server") webhookPatcher := wk.NewWebhookPatcher() svc := env.Config.WebhookService ns := env.Config.WebhookNS @@ -345,7 +332,7 @@ func patchAdmissionWebhook() { env.Config.WebhookCertSecret, ns) if err != nil { - setupLog.Error(err, "Can not update CA bundle for GKO validation webhook. GKO can not start") + log.Global.Error(err, "Can not update CA bundle for GKO validation webhook. GKO can not start") panic(err) } @@ -355,7 +342,7 @@ func patchAdmissionWebhook() { env.Config.WebhookCertSecret, ns) if err != nil { - setupLog.Error(err, "Can not update CA bundle for GKO mutation webhook. GKO can not start") + log.Global.Error(err, "Can not update CA bundle for GKO mutation webhook. GKO can not start") panic(err) } }