Skip to content

Commit fce0e5b

Browse files
committed
logging - migrate the whole code to LogI, LogD, LogE functions
Change-Id: Iec310acdd50f805e03b6291ea1c2bc3771563a9f
1 parent 3840f7d commit fce0e5b

File tree

13 files changed

+123
-121
lines changed

13 files changed

+123
-121
lines changed

cli/cmd/utils/utils.go

Lines changed: 31 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ import (
5353
opv1 "github.com/operator-framework/api/pkg/operators/v1alpha1"
5454
sfv1 "github.com/softwarefactory-project/sf-operator/api/v1"
5555
controllers "github.com/softwarefactory-project/sf-operator/controllers"
56+
ctrlutils "github.com/softwarefactory-project/sf-operator/controllers/libs/utils"
5657

5758
"k8s.io/client-go/kubernetes"
5859
)
@@ -137,21 +138,6 @@ func SetLogger(command *cobra.Command) {
137138
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
138139
}
139140

140-
// logI logs a message with the INFO log Level
141-
func logI(msg string) {
142-
ctrl.Log.Info(msg)
143-
}
144-
145-
// logI logs a message with the DEBUG log Level
146-
func logD(msg string) {
147-
ctrl.Log.V(1).Info(msg)
148-
}
149-
150-
// logI logs a message with the Error log Level
151-
func logE(err error, msg string) {
152-
ctrl.Log.Error(err, msg)
153-
}
154-
155141
func GetCLIContext(command *cobra.Command) (SoftwareFactoryConfigContext, error) {
156142

157143
// This is usually called for every CLI command so here let's set the Logger settings
@@ -164,10 +150,10 @@ func GetCLIContext(command *cobra.Command) (SoftwareFactoryConfigContext, error)
164150
if configPath != "" {
165151
ctxName, cliContext, err = getContextFromFile(command)
166152
if err != nil {
167-
logE(err, "Could not load config file")
153+
ctrlutils.LogE(err, "Could not load config file")
168154
os.Exit(1)
169155
} else {
170-
logD("Using configuration context " + ctxName)
156+
ctrlutils.LogD("Using configuration context " + ctxName)
171157
}
172158
}
173159
// Override with defaults
@@ -190,12 +176,12 @@ func GetCLIContext(command *cobra.Command) (SoftwareFactoryConfigContext, error)
190176
if cliContext.Dev.SFOperatorRepositoryPath == "" {
191177
defaultSFOperatorRepositoryPath, getwdErr := os.Getwd()
192178
if getwdErr != nil {
193-
logE(getwdErr,
179+
ctrlutils.LogE(getwdErr,
194180
"sf-operator-repository-path is not set in `dev` section of the configuration file and unable to determine the current working directory")
195181
os.Exit(1)
196182
}
197183
cliContext.Dev.SFOperatorRepositoryPath = defaultSFOperatorRepositoryPath
198-
logD("Using current working directory for sf-operator-repository-path: " + cliContext.Dev.SFOperatorRepositoryPath)
184+
ctrlutils.LogD("Using current working directory for sf-operator-repository-path: " + cliContext.Dev.SFOperatorRepositoryPath)
199185
}
200186
return cliContext, nil
201187
}
@@ -239,7 +225,7 @@ func CreateKubernetesClient(contextName string) (client.Client, error) {
239225
func CreateKubernetesClientOrDie(contextName string) client.Client {
240226
cli, err := CreateKubernetesClient(contextName)
241227
if err != nil {
242-
ctrl.Log.Error(err, "Error creating Kubernetes client")
228+
ctrlutils.LogE(err, "Error creating Kubernetes client")
243229
os.Exit(1)
244230
}
245231
return cli
@@ -249,7 +235,7 @@ func GetCLIENV(kmd *cobra.Command) (string, ENV) {
249235

250236
cliCtx, err := GetCLIContext(kmd)
251237
if err != nil {
252-
ctrl.Log.Error(err, "Error initializing CLI:")
238+
ctrlutils.LogE(err, "Error initializing CLI:")
253239
os.Exit(1)
254240
}
255241

@@ -283,7 +269,7 @@ func DeleteOrDie(env *ENV, obj client.Object, opts ...client.DeleteOption) bool
283269
return false
284270
} else if err != nil {
285271
msg := fmt.Sprintf("Error while deleting %s \"%s\"", reflect.TypeOf(obj).Name(), obj.GetName())
286-
ctrl.Log.Error(err, msg)
272+
ctrlutils.LogE(err, msg)
287273
os.Exit(1)
288274
}
289275
return true
@@ -295,49 +281,49 @@ func GetMOrDie(env *ENV, name string, obj client.Object) bool {
295281
return false
296282
} else if err != nil {
297283
msg := fmt.Sprintf("Error while fetching %s \"%s\"", reflect.TypeOf(obj).Name(), name)
298-
ctrl.Log.Error(err, msg)
284+
ctrlutils.LogE(err, msg)
299285
os.Exit(1)
300286
}
301287
return true
302288
}
303289

304290
func UpdateROrDie(env *ENV, obj client.Object) {
305291
var msg = fmt.Sprintf("Updating %s \"%s\" in %s", reflect.TypeOf(obj).Name(), obj.GetName(), env.Ns)
306-
ctrl.Log.Info(msg)
292+
ctrlutils.LogI(msg)
307293
if err := env.Cli.Update(env.Ctx, obj); err != nil {
308294
msg = fmt.Sprintf("Error while updating %s \"%s\"", reflect.TypeOf(obj).Name(), obj.GetName())
309-
ctrl.Log.Error(err, msg)
295+
ctrlutils.LogE(err, msg)
310296
os.Exit(1)
311297
}
312298
msg = fmt.Sprintf("%s \"%s\" updated", reflect.TypeOf(obj).Name(), obj.GetName())
313-
ctrl.Log.Info(msg)
299+
ctrlutils.LogI(msg)
314300
}
315301

316302
func CreateROrDie(env *ENV, obj client.Object) {
317303
var msg = fmt.Sprintf("Creating %s \"%s\" in %s", reflect.TypeOf(obj).Name(), obj.GetName(), env.Ns)
318-
ctrl.Log.Info(msg)
304+
ctrlutils.LogI(msg)
319305
obj.SetNamespace(env.Ns)
320306
if err := env.Cli.Create(env.Ctx, obj); err != nil {
321307
msg = fmt.Sprintf("Error while creating %s \"%s\"", reflect.TypeOf(obj).Name(), obj.GetName())
322-
ctrl.Log.Error(err, msg)
308+
ctrlutils.LogE(err, msg)
323309
os.Exit(1)
324310
}
325311
msg = fmt.Sprintf("%s \"%s\" created", reflect.TypeOf(obj).Name(), obj.GetName())
326-
ctrl.Log.Info(msg)
312+
ctrlutils.LogI(msg)
327313
}
328314

329315
func DeleteAllOfOrDie(env *ENV, obj client.Object, opts ...client.DeleteAllOfOption) {
330316
if err := env.Cli.DeleteAllOf(env.Ctx, obj, opts...); err != nil {
331317
var msg = "Error while deleting"
332-
ctrl.Log.Error(err, msg)
318+
ctrlutils.LogE(err, msg)
333319
os.Exit(1)
334320
}
335321
}
336322

337323
func GetCLIctxOrDie(kmd *cobra.Command, args []string, allowedArgs []string) SoftwareFactoryConfigContext {
338324
cliCtx, err := GetCLIContext(kmd)
339325
if err != nil {
340-
ctrl.Log.Error(err, "Error initializing:")
326+
ctrlutils.LogE(err, "Error initializing:")
341327
os.Exit(1)
342328
}
343329
if len(allowedArgs) == 0 {
@@ -346,15 +332,15 @@ func GetCLIctxOrDie(kmd *cobra.Command, args []string, allowedArgs []string) Sof
346332
} else {
347333
argumentError := errors.New("argument must be in: " + strings.Join(allowedArgs, ", "))
348334
if len(args) != 1 {
349-
ctrl.Log.Error(argumentError, "Need one argument")
335+
ctrlutils.LogE(argumentError, "Need one argument")
350336
os.Exit(1)
351337
}
352338
for _, a := range allowedArgs {
353339
if args[0] == a {
354340
return cliCtx
355341
}
356342
}
357-
ctrl.Log.Error(argumentError, "Unknown argument "+args[0])
343+
ctrlutils.LogE(argumentError, "Unknown argument "+args[0])
358344
os.Exit(1)
359345
}
360346
return SoftwareFactoryConfigContext{}
@@ -380,8 +366,8 @@ func RunCmdWithEnvOrDie(environ []string, cmd string, args ...string) string {
380366
kmd.Env = append(os.Environ(), environ...)
381367
out, err := kmd.CombinedOutput()
382368
if err != nil {
383-
logE(err, "Could not run command '"+cmd+"'")
384-
logI("Captured output:\n" + string(out))
369+
ctrlutils.LogE(err, "Could not run command '"+cmd+"'")
370+
ctrlutils.LogI("Captured output:\n" + string(out))
385371
os.Exit(1)
386372
}
387373
return string(out)
@@ -397,7 +383,7 @@ func EnsureNamespaceOrDie(env *ENV, name string) {
397383
ns.Name = name
398384
CreateROrDie(env, &ns)
399385
} else if err != nil {
400-
ctrl.Log.Error(err, "Error checking namespace "+name)
386+
ctrlutils.LogE(err, "Error checking namespace "+name)
401387
os.Exit(1)
402388
}
403389
}
@@ -412,7 +398,7 @@ func EnsureServiceAccountOrDie(env *ENV, name string) {
412398
func WriteContentToFile(filePath string, content []byte, mode fs.FileMode) {
413399
err := os.WriteFile(filePath, content, mode)
414400
if err != nil {
415-
ctrl.Log.Error(err, "Can not write a file "+filePath)
401+
ctrlutils.LogE(err, "Can not write a file "+filePath)
416402
os.Exit(1)
417403
}
418404
}
@@ -425,7 +411,7 @@ func VarListToMap(varsList []string) map[string]string {
425411
tokens := strings.Split(v, "=")
426412

427413
if len(tokens) != 2 {
428-
ctrl.Log.Error(errors.New("parse error"), "parsed value `"+v+"` needs to be defined as 'foo=bar'")
414+
ctrlutils.LogE(errors.New("parse error"), "parsed value `"+v+"` needs to be defined as 'foo=bar'")
429415
os.Exit(1)
430416
}
431417
vars[tokens[0]] = tokens[1]
@@ -436,7 +422,7 @@ func VarListToMap(varsList []string) map[string]string {
436422
func CreateDirectory(dirPath string, mode fs.FileMode) {
437423
err := os.MkdirAll(dirPath, mode)
438424
if err != nil {
439-
ctrl.Log.Error(err, "Can not create directory "+dirPath)
425+
ctrlutils.LogE(err, "Can not create directory "+dirPath)
440426
os.Exit(1)
441427
}
442428
}
@@ -454,7 +440,7 @@ func GetClientset(kubeContext string) (*rest.Config, *kubernetes.Clientset) {
454440
restConfig := controllers.GetConfigContextOrDie(kubeContext)
455441
kubeClientset, err := kubernetes.NewForConfig(restConfig)
456442
if err != nil {
457-
ctrl.Log.Error(err, "Could not instantiate Clientset")
443+
ctrlutils.LogE(err, "Could not instantiate Clientset")
458444
os.Exit(1)
459445
}
460446
return restConfig, kubeClientset
@@ -482,7 +468,7 @@ func RunRemoteCmd(kubeContext string, namespace string, podName string, containe
482468
if err != nil {
483469
errMsg := fmt.Sprintf("Command \"%s\" [Pod: %s - Container: %s] failed with the following stderr: %s",
484470
strings.Join(cmdArgs, " "), podName, containerName, errorBuffer.String())
485-
ctrl.Log.Error(err, errMsg)
471+
ctrlutils.LogE(err, errMsg)
486472
os.Exit(1)
487473
}
488474
return buffer
@@ -493,10 +479,10 @@ func ReadYAMLToMapOrDie(filePath string) map[string]interface{} {
493479
secretContent := make(map[string]interface{})
494480
err := yaml.Unmarshal(readFile, &secretContent)
495481
if err != nil {
496-
ctrl.Log.Error(err, "Problem on reading the file content")
482+
ctrlutils.LogE(err, "Problem on reading the file content")
497483
}
498484
if len(secretContent) == 0 {
499-
ctrl.Log.Error(errors.New("file is empty"), "The file is empty or it does not exist!")
485+
ctrlutils.LogE(errors.New("file is empty"), "The file is empty or it does not exist!")
500486
os.Exit(1)
501487
}
502488
return secretContent
@@ -505,7 +491,7 @@ func ReadYAMLToMapOrDie(filePath string) map[string]interface{} {
505491
func GetKubectlPath() string {
506492
kubectlPath, err := exec.LookPath("kubectl")
507493
if err != nil {
508-
ctrl.Log.Error(errors.New("no kubectl binary"),
494+
ctrlutils.LogE(errors.New("no kubectl binary"),
509495
"No 'kubectl' binary found. Please install the 'kubectl' binary before attempting a restore")
510496
os.Exit(1)
511497
}
@@ -519,7 +505,7 @@ func ExecuteKubectlClient(ns string, podName string, containerName string, execu
519505

520506
err := cmd.Run()
521507
if err != nil {
522-
ctrl.Log.Error(err, "There is an issue on executing command: "+executeCommand)
508+
ctrlutils.LogE(err, "There is an issue on executing command: "+executeCommand)
523509
os.Exit(1)
524510
}
525511

controllers/config.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ func (r *SFController) SetupBaseSecrets(internalTenantSecretsVersion string) boo
9191
var secret apiv1.Secret
9292
secretName := "config-update-secrets"
9393
if !r.GetM(secretName, &secret) {
94-
r.log.V(1).Info("Creating the config-update service account secret")
94+
utils.LogI("Creating the config-update service account secret")
9595
secret = apiv1.Secret{
9696
Type: "kubernetes.io/service-account-token",
9797
ObjectMeta: metav1.ObjectMeta{
@@ -129,13 +129,13 @@ func (r *SFController) SetupBaseSecrets(internalTenantSecretsVersion string) boo
129129
}
130130

131131
if !found {
132-
r.log.V(1).Info("Creating base secret job")
132+
utils.LogI("Creating base secret job")
133133
r.CreateR(r.RunCommand(jobName, []string{"config-create-zuul-secrets"}, extraCmdVars))
134134
return false
135135
} else if job.Status.Succeeded >= 1 {
136136
return true
137137
} else {
138-
r.log.V(1).Info("Waiting for base secret job result")
138+
utils.LogI("Waiting for base secret job result")
139139
return false
140140
}
141141
}
@@ -213,7 +213,7 @@ func (r *SFController) SetupConfigJob() bool {
213213
// This ensures that the zuul-scheduler loaded the provisionned Zuul config
214214
// for the 'internal' tenant
215215
if needReconfigureTenant {
216-
r.log.Info("Running tenant-reconfigure for the 'internal' tenant")
216+
utils.LogI("Running tenant-reconfigure for the 'internal' tenant")
217217
if r.runZuulInternalTenantReconfigure() {
218218
// Create an empty ConfigMap to keep note the reconfigure has been already done
219219
zsInternalTenantReconfigure.ObjectMeta = metav1.ObjectMeta{

controllers/gateway.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ func (r *SFController) DeployHTTPDGateway() bool {
5454
current := appsv1.Deployment{}
5555
if r.GetM(ident, &current) {
5656
if !utils.MapEquals(&current.Spec.Template.ObjectMeta.Annotations, &annotations) {
57-
r.log.V(1).Info("gateway configuration changed, rollout gateway pods ...")
57+
utils.LogI("gateway configuration changed, rollout gateway pods ...")
5858
current.Spec = dep.DeepCopy().Spec
5959
r.UpdateR(&current)
6060
return false

controllers/libs/utils/utils.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"golang.org/x/crypto/ssh"
2323
"gopkg.in/ini.v1"
2424
"k8s.io/apimachinery/pkg/api/resource"
25+
ctrl "sigs.k8s.io/controller-runtime"
2526
)
2627

2728
// GetEnvVarValue returns the value of the named env var. Return an empty string when not found.
@@ -38,6 +39,21 @@ func BoolPtr(b bool) *bool { return &b }
3839

3940
var Execmod int32 = 493 // decimal for 0755 octal
4041

42+
// LogI logs a message with the INFO log Level
43+
func LogI(msg string) {
44+
ctrl.Log.Info(msg)
45+
}
46+
47+
// LogD logs a message with the DEBUG log Level
48+
func LogD(msg string) {
49+
ctrl.Log.V(1).Info(msg)
50+
}
51+
52+
// LogE logs a message with the Error log Level
53+
func LogE(err error, msg string) {
54+
ctrl.Log.Error(err, msg)
55+
}
56+
4157
// NewUUIDString produce a UUID
4258
func NewUUIDString() string {
4359
return uuid.New().String()

controllers/logserver.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ func (r *SFController) ensureLogserverPodMonitor() bool {
7070
return false
7171
} else {
7272
if !utils.MapEquals(&currentLspm.ObjectMeta.Annotations, &annotations) {
73-
r.log.V(1).Info("Logserver PodMonitor configuration changed, updating...")
73+
utils.LogI("Logserver PodMonitor configuration changed, updating...")
7474
currentLspm.Spec = desiredLsPodmonitor.Spec
7575
currentLspm.ObjectMeta.Annotations = annotations
7676
r.UpdateR(&currentLspm)
@@ -106,7 +106,7 @@ func (r *SFController) ensureLogserverPromRule() bool {
106106
return false
107107
} else {
108108
if !utils.MapEquals(&currentPromRule.ObjectMeta.Annotations, &annotations) {
109-
r.log.V(1).Info("Logserver default Prometheus rules changed, updating...")
109+
utils.LogI("Logserver default Prometheus rules changed, updating...")
110110
currentPromRule.Spec = desiredLsPromRule.Spec
111111
currentPromRule.ObjectMeta.Annotations = annotations
112112
r.UpdateR(&currentPromRule)

controllers/mariadb.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ GRANT ALL ON *.* TO root@'%%' WITH GRANT OPTION;`,
308308
Data: nil,
309309
}
310310
if !r.GetM(zuulDBConfigSecret, &zuulDBSecret) {
311-
r.log.V(1).Info("Starting DB Post Init")
311+
utils.LogI("Starting DB Post Init")
312312
zuulDBSecret = r.DBPostInit(zuulDBSecret)
313313
}
314314
}

controllers/nodepool.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ func (r *SFController) ensureNodepoolPromRule(cloudsYaml map[string]interface{})
341341
return false
342342
} else {
343343
if !utils.MapEquals(&currentPromRule.ObjectMeta.Annotations, &annotations) {
344-
r.log.V(1).Info("Nodepool default Prometheus rules changed, updating...")
344+
utils.LogI("Nodepool default Prometheus rules changed, updating...")
345345
currentPromRule.Spec = desiredNodepoolPromRule.Spec
346346
currentPromRule.ObjectMeta.Annotations = annotations
347347
r.UpdateR(&currentPromRule)
@@ -790,7 +790,7 @@ func (r *SFController) DeployNodepoolLauncher(statsdExporterVolume apiv1.Volume,
790790
current := appsv1.Deployment{}
791791
if r.GetM(LauncherIdent, &current) {
792792
if !utils.MapEquals(&current.Spec.Template.ObjectMeta.Annotations, &annotations) {
793-
r.log.V(1).Info("Nodepool-launcher configuration changed, rollout pods ...")
793+
utils.LogI("Nodepool-launcher configuration changed, rollout pods ...")
794794
current.Spec = nl.DeepCopy().Spec
795795
r.UpdateR(&current)
796796
return false

0 commit comments

Comments
 (0)