Skip to content

Commit 39b6a5c

Browse files
committed
utils: Add LogTrace and improve structured logging helpers
Move logging-related functions from the generic `libs/utils` package to the `libs/logging` package. - Introduce LogTrace, a helper for logging at high verbosity (level 5). - Add LogW and LogDeprecation to provide structured warning messages. - Refactor LogD to delegate to an internal logAtLevel function. - Replace all ctrl.Log.V(5).Info calls with LogTrace. - Add unit tests for LogI, LogD, LogTrace, LogW, LogDeprecation, and LogE. Change-Id: Id3e777983883100890fdc937992b8787dcf672bb
1 parent 8a02a44 commit 39b6a5c

File tree

18 files changed

+253
-129
lines changed

18 files changed

+253
-129
lines changed

cli/cmd/dev/gerrit/gerrit.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import (
4646

4747
cliutils "github.com/softwarefactory-project/sf-operator/cli/cmd/utils"
4848
"github.com/softwarefactory-project/sf-operator/controllers/libs/base"
49+
"github.com/softwarefactory-project/sf-operator/controllers/libs/logging"
4950
cutils "github.com/softwarefactory-project/sf-operator/controllers/libs/utils"
5051
)
5152

@@ -526,7 +527,7 @@ func GetAdminRepoURL(env *cliutils.ENV, fqdn string, repoName string) string {
526527
os.Exit(1)
527528
}
528529
apiKey := string(gerritAPIKey.Data["gerrit-admin-api-key"])
529-
ctrl.Log.V(5).Info("API Key: " + apiKey)
530+
logging.LogTrace("API Key: " + apiKey)
530531
repoURL := fmt.Sprintf("https://admin:%s@gerrit.%s/a/%s", apiKey, fqdn, repoName)
531532
return repoURL
532533
}
@@ -544,9 +545,9 @@ func CloneAsAdmin(env *cliutils.ENV, fqdn string, repoName string, dest string,
544545
}
545546
args = append(args, "clone", repoURL, dest)
546547
output = cliutils.RunCmdOrDie("git", args...)
547-
ctrl.Log.V(5).Info("captured output:\n" + output)
548+
logging.LogTrace("captured output:\n" + output)
548549
output = cliutils.RunCmdOrDie("git", "-C", dest, "remote", "add", "gerrit", repoURL)
549-
ctrl.Log.V(5).Info("captured output:\n" + output)
550+
logging.LogTrace("captured output:\n" + output)
550551
} else {
551552
ctrl.Log.Info("Repository exists. Resetting remotes...")
552553
for _, o := range []string{
@@ -555,7 +556,7 @@ func CloneAsAdmin(env *cliutils.ENV, fqdn string, repoName string, dest string,
555556
cliutils.RunCmdOrDie("git", "-C", dest, "fetch", "origin"),
556557
} {
557558
if o != "" {
558-
ctrl.Log.V(5).Info("captured output:\n" + o)
559+
logging.LogTrace("captured output:\n" + o)
559560
}
560561
}
561562
}
@@ -573,14 +574,14 @@ func CloneAsAdmin(env *cliutils.ENV, fqdn string, repoName string, dest string,
573574
} {
574575
output = cliutils.RunCmdOrDie("git", _args...)
575576
if output != "" {
576-
ctrl.Log.V(5).Info("captured output:\n" + output)
577+
logging.LogTrace("captured output:\n" + output)
577578
}
578579
}
579580
if !verify {
580581
output = cliutils.RunCmdOrDie("git",
581582
"-C", dest, "config", "http.sslverify", "false")
582583
if output != "" {
583-
ctrl.Log.V(5).Info("captured output:\n" + output)
584+
logging.LogTrace("captured output:\n" + output)
584585
}
585586
}
586587
}

cli/cmd/nodepool.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222

2323
cliutils "github.com/softwarefactory-project/sf-operator/cli/cmd/utils"
2424
"github.com/softwarefactory-project/sf-operator/controllers"
25+
"github.com/softwarefactory-project/sf-operator/controllers/libs/logging"
2526
"github.com/spf13/cobra"
2627
"k8s.io/client-go/tools/clientcmd"
2728
ctrl "sigs.k8s.io/controller-runtime"
@@ -70,9 +71,9 @@ func npCreate(kmd *cobra.Command, args []string) {
7071
skipProvidersSecrets, _ := kmd.Flags().GetBool("skip-providers-secrets")
7172

7273
if nodepoolContext == kubeContext {
73-
ctrl.Log.Info("Warning: Nodepool will use the same cluster context as SF")
74+
logging.LogW("Nodepool will use the same cluster context as SF")
7475
if nodepoolNamespace == ns {
75-
ctrl.Log.Info("Warning: Nodepool will manage resources in the same namespace as the Software Factory deployment")
76+
logging.LogW("Nodepool will manage resources in the same namespace as the Software Factory deployment")
7677
}
7778
}
7879
CreateNamespaceForNodepool(&sfEnv, nodepoolContext, nodepoolNamespace, skipProvidersSecrets)

cli/cmd/utils/utils.go

Lines changed: 33 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ import (
6060
opv1 "github.com/operator-framework/api/pkg/operators/v1alpha1"
6161
sfv1 "github.com/softwarefactory-project/sf-operator/api/v1"
6262
controllers "github.com/softwarefactory-project/sf-operator/controllers"
63-
ctrlutils "github.com/softwarefactory-project/sf-operator/controllers/libs/utils"
63+
"github.com/softwarefactory-project/sf-operator/controllers/libs/logging"
6464

6565
"k8s.io/client-go/kubernetes"
6666

@@ -167,10 +167,10 @@ func GetCLIContext(command *cobra.Command) (SoftwareFactoryConfigContext, error)
167167
if configPath != "" {
168168
ctxName, cliContext, err = getContextFromFile(command)
169169
if err != nil {
170-
ctrlutils.LogE(err, "Could not load config file")
170+
logging.LogE(err, "Could not load config file")
171171
os.Exit(1)
172172
} else {
173-
ctrlutils.LogD("Using configuration context " + ctxName)
173+
logging.LogD("Using configuration context " + ctxName)
174174
}
175175
}
176176
// Override with defaults
@@ -217,12 +217,12 @@ func GetCLIContext(command *cobra.Command) (SoftwareFactoryConfigContext, error)
217217
if cliContext.Dev.SFOperatorRepositoryPath == "" {
218218
defaultSFOperatorRepositoryPath, getwdErr := os.Getwd()
219219
if getwdErr != nil {
220-
ctrlutils.LogE(getwdErr,
220+
logging.LogE(getwdErr,
221221
"sf-operator-repository-path is not set in `dev` section of the configuration file and unable to determine the current working directory")
222222
os.Exit(1)
223223
}
224224
cliContext.Dev.SFOperatorRepositoryPath = defaultSFOperatorRepositoryPath
225-
ctrlutils.LogD("Using current working directory for sf-operator-repository-path: " + cliContext.Dev.SFOperatorRepositoryPath)
225+
logging.LogD("Using current working directory for sf-operator-repository-path: " + cliContext.Dev.SFOperatorRepositoryPath)
226226
}
227227
return cliContext, nil
228228
}
@@ -267,7 +267,7 @@ func CreateKubernetesClient(contextName string) (client.Client, error) {
267267
func CreateKubernetesClientOrDie(contextName string) client.Client {
268268
cli, err := CreateKubernetesClient(contextName)
269269
if err != nil {
270-
ctrlutils.LogE(err, "Error creating Kubernetes client")
270+
logging.LogE(err, "Error creating Kubernetes client")
271271
os.Exit(1)
272272
}
273273
return cli
@@ -277,7 +277,7 @@ func GetCLIENV(kmd *cobra.Command) (string, ENV) {
277277

278278
cliCtx, err := GetCLIContext(kmd)
279279
if err != nil {
280-
ctrlutils.LogE(err, "Error initializing CLI:")
280+
logging.LogE(err, "Error initializing CLI:")
281281
os.Exit(1)
282282
}
283283

@@ -311,7 +311,7 @@ func DeleteOrDie(env *ENV, obj client.Object, opts ...client.DeleteOption) bool
311311
return false
312312
} else if err != nil {
313313
msg := fmt.Sprintf("Error while deleting %s \"%s\"", reflect.TypeOf(obj).Name(), obj.GetName())
314-
ctrlutils.LogE(err, msg)
314+
logging.LogE(err, msg)
315315
os.Exit(1)
316316
}
317317
return true
@@ -323,49 +323,49 @@ func GetMOrDie(env *ENV, name string, obj client.Object) bool {
323323
return false
324324
} else if err != nil {
325325
msg := fmt.Sprintf("Error while fetching %s \"%s\"", reflect.TypeOf(obj).Name(), name)
326-
ctrlutils.LogE(err, msg)
326+
logging.LogE(err, msg)
327327
os.Exit(1)
328328
}
329329
return true
330330
}
331331

332332
func UpdateROrDie(env *ENV, obj client.Object) {
333333
var msg = fmt.Sprintf("Updating %s \"%s\" in %s", reflect.TypeOf(obj).Name(), obj.GetName(), env.Ns)
334-
ctrlutils.LogI(msg)
334+
logging.LogI(msg)
335335
if err := env.Cli.Update(env.Ctx, obj); err != nil {
336336
msg = fmt.Sprintf("Error while updating %s \"%s\"", reflect.TypeOf(obj).Name(), obj.GetName())
337-
ctrlutils.LogE(err, msg)
337+
logging.LogE(err, msg)
338338
os.Exit(1)
339339
}
340340
msg = fmt.Sprintf("%s \"%s\" updated", reflect.TypeOf(obj).Name(), obj.GetName())
341-
ctrlutils.LogI(msg)
341+
logging.LogI(msg)
342342
}
343343

344344
func CreateROrDie(env *ENV, obj client.Object) {
345345
var msg = fmt.Sprintf("Creating %s \"%s\" in %s", reflect.TypeOf(obj).Name(), obj.GetName(), env.Ns)
346-
ctrlutils.LogI(msg)
346+
logging.LogI(msg)
347347
obj.SetNamespace(env.Ns)
348348
if err := env.Cli.Create(env.Ctx, obj); err != nil {
349349
msg = fmt.Sprintf("Error while creating %s \"%s\"", reflect.TypeOf(obj).Name(), obj.GetName())
350-
ctrlutils.LogE(err, msg)
350+
logging.LogE(err, msg)
351351
os.Exit(1)
352352
}
353353
msg = fmt.Sprintf("%s \"%s\" created", reflect.TypeOf(obj).Name(), obj.GetName())
354-
ctrlutils.LogI(msg)
354+
logging.LogI(msg)
355355
}
356356

357357
func DeleteAllOfOrDie(env *ENV, obj client.Object, opts ...client.DeleteAllOfOption) {
358358
if err := env.Cli.DeleteAllOf(env.Ctx, obj, opts...); err != nil {
359359
var msg = "Error while deleting"
360-
ctrlutils.LogE(err, msg)
360+
logging.LogE(err, msg)
361361
os.Exit(1)
362362
}
363363
}
364364

365365
func GetCLIctxOrDie(kmd *cobra.Command, args []string, allowedArgs []string) SoftwareFactoryConfigContext {
366366
cliCtx, err := GetCLIContext(kmd)
367367
if err != nil {
368-
ctrlutils.LogE(err, "Error initializing:")
368+
logging.LogE(err, "Error initializing:")
369369
os.Exit(1)
370370
}
371371
if len(allowedArgs) == 0 {
@@ -374,15 +374,15 @@ func GetCLIctxOrDie(kmd *cobra.Command, args []string, allowedArgs []string) Sof
374374
} else {
375375
argumentError := errors.New("argument must be in: " + strings.Join(allowedArgs, ", "))
376376
if len(args) != 1 {
377-
ctrlutils.LogE(argumentError, "Need one argument")
377+
logging.LogE(argumentError, "Need one argument")
378378
os.Exit(1)
379379
}
380380
for _, a := range allowedArgs {
381381
if args[0] == a {
382382
return cliCtx
383383
}
384384
}
385-
ctrlutils.LogE(argumentError, "Unknown argument "+args[0])
385+
logging.LogE(argumentError, "Unknown argument "+args[0])
386386
os.Exit(1)
387387
}
388388
return SoftwareFactoryConfigContext{}
@@ -408,8 +408,8 @@ func RunCmdWithEnvOrDie(environ []string, cmd string, args ...string) string {
408408
kmd.Env = append(os.Environ(), environ...)
409409
out, err := kmd.CombinedOutput()
410410
if err != nil {
411-
ctrlutils.LogE(err, "Could not run command '"+cmd+"'")
412-
ctrlutils.LogI("Captured output:\n" + string(out))
411+
logging.LogE(err, "Could not run command '"+cmd+"'")
412+
logging.LogI("Captured output:\n" + string(out))
413413
os.Exit(1)
414414
}
415415
return string(out)
@@ -425,7 +425,7 @@ func EnsureNamespaceOrDie(env *ENV, name string) {
425425
ns.Name = name
426426
CreateROrDie(env, &ns)
427427
} else if err != nil {
428-
ctrlutils.LogE(err, "Error checking namespace "+name)
428+
logging.LogE(err, "Error checking namespace "+name)
429429
os.Exit(1)
430430
}
431431
}
@@ -440,7 +440,7 @@ func EnsureServiceAccountOrDie(env *ENV, name string) {
440440
func WriteContentToFile(filePath string, content []byte, mode fs.FileMode) {
441441
err := os.WriteFile(filePath, content, mode)
442442
if err != nil {
443-
ctrlutils.LogE(err, "Can not write a file "+filePath)
443+
logging.LogE(err, "Can not write a file "+filePath)
444444
os.Exit(1)
445445
}
446446
}
@@ -453,7 +453,7 @@ func VarListToMap(varsList []string) map[string]string {
453453
tokens := strings.Split(v, "=")
454454

455455
if len(tokens) != 2 {
456-
ctrlutils.LogE(errors.New("parse error"), "parsed value `"+v+"` needs to be defined as 'foo=bar'")
456+
logging.LogE(errors.New("parse error"), "parsed value `"+v+"` needs to be defined as 'foo=bar'")
457457
os.Exit(1)
458458
}
459459
vars[tokens[0]] = tokens[1]
@@ -464,7 +464,7 @@ func VarListToMap(varsList []string) map[string]string {
464464
func CreateDirectory(dirPath string, mode fs.FileMode) {
465465
err := os.MkdirAll(dirPath, mode)
466466
if err != nil {
467-
ctrlutils.LogE(err, "Can not create directory "+dirPath)
467+
logging.LogE(err, "Can not create directory "+dirPath)
468468
os.Exit(1)
469469
}
470470
}
@@ -482,7 +482,7 @@ func GetClientset(kubeContext string) (*rest.Config, *kubernetes.Clientset) {
482482
restConfig := controllers.GetConfigContextOrDie(kubeContext)
483483
kubeClientset, err := kubernetes.NewForConfig(restConfig)
484484
if err != nil {
485-
ctrlutils.LogE(err, "Could not instantiate Clientset")
485+
logging.LogE(err, "Could not instantiate Clientset")
486486
os.Exit(1)
487487
}
488488
return restConfig, kubeClientset
@@ -510,7 +510,7 @@ func RunRemoteCmd(kubeContext string, namespace string, podName string, containe
510510
if err != nil {
511511
errMsg := fmt.Sprintf("Command \"%s\" [Pod: %s - Container: %s] failed with the following stderr: %s",
512512
strings.Join(cmdArgs, " "), podName, containerName, errorBuffer.String())
513-
ctrlutils.LogE(err, errMsg)
513+
logging.LogE(err, errMsg)
514514
os.Exit(1)
515515
}
516516
return buffer
@@ -521,10 +521,10 @@ func ReadYAMLToMapOrDie(filePath string) map[string]interface{} {
521521
secretContent := make(map[string]interface{})
522522
err := yaml.Unmarshal(readFile, &secretContent)
523523
if err != nil {
524-
ctrlutils.LogE(err, "Problem on reading the file content")
524+
logging.LogE(err, "Problem on reading the file content")
525525
}
526526
if len(secretContent) == 0 {
527-
ctrlutils.LogE(errors.New("file is empty"), "The file is empty or it does not exist!")
527+
logging.LogE(errors.New("file is empty"), "The file is empty or it does not exist!")
528528
os.Exit(1)
529529
}
530530
return secretContent
@@ -533,7 +533,7 @@ func ReadYAMLToMapOrDie(filePath string) map[string]interface{} {
533533
func GetKubectlPath() string {
534534
kubectlPath, err := exec.LookPath("kubectl")
535535
if err != nil {
536-
ctrlutils.LogE(errors.New("no kubectl binary"),
536+
logging.LogE(errors.New("no kubectl binary"),
537537
"No 'kubectl' binary found. Please install the 'kubectl' binary before attempting a restore")
538538
os.Exit(1)
539539
}
@@ -547,7 +547,7 @@ func ExecuteKubectlClient(ns string, podName string, containerName string, execu
547547

548548
err := cmd.Run()
549549
if err != nil {
550-
ctrlutils.LogE(err, "There is an issue on executing command: "+executeCommand)
550+
logging.LogE(err, "There is an issue on executing command: "+executeCommand)
551551
os.Exit(1)
552552
}
553553

@@ -556,7 +556,7 @@ func ExecuteKubectlClient(ns string, podName string, containerName string, execu
556556
func GetKubeConfig() *clientcmdapi.Config {
557557
clientCfg, err := clientcmd.NewDefaultClientConfigLoadingRules().Load()
558558
if err != nil {
559-
ctrlutils.LogE(err, "Could not find the kubeconfig")
559+
logging.LogE(err, "Could not find the kubeconfig")
560560
os.Exit(1)
561561
}
562562
return clientCfg
@@ -580,7 +580,7 @@ func GetKubeConfigContextByName(contextName string) (*clientcmdapi.Context, stri
580580
// Load the context
581581
context, err := clientCfg.Contexts[contextName]
582582
if !err {
583-
ctrlutils.LogD("could not find the context " + contextName)
583+
logging.LogD("could not find the context " + contextName)
584584
}
585585
return context, contextName
586586
}

controllers/config.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
_ "embed"
1010

1111
"github.com/softwarefactory-project/sf-operator/controllers/libs/base"
12+
"github.com/softwarefactory-project/sf-operator/controllers/libs/logging"
1213
"github.com/softwarefactory-project/sf-operator/controllers/libs/utils"
1314
batchv1 "k8s.io/api/batch/v1"
1415
apiv1 "k8s.io/api/core/v1"
@@ -91,7 +92,7 @@ func (r *SFController) SetupBaseSecrets(internalTenantSecretsVersion string) boo
9192
var secret apiv1.Secret
9293
secretName := "config-update-secrets"
9394
if !r.GetM(secretName, &secret) {
94-
utils.LogI("Creating the config-update service account secret")
95+
logging.LogI("Creating the config-update service account secret")
9596
secret = apiv1.Secret{
9697
Type: "kubernetes.io/service-account-token",
9798
ObjectMeta: metav1.ObjectMeta{
@@ -129,13 +130,13 @@ func (r *SFController) SetupBaseSecrets(internalTenantSecretsVersion string) boo
129130
}
130131

131132
if !found {
132-
utils.LogI("Creating base secret job")
133+
logging.LogI("Creating base secret job")
133134
r.CreateR(r.RunCommand(jobName, []string{"config-create-zuul-secrets"}, extraCmdVars))
134135
return false
135136
} else if job.Status.Succeeded >= 1 {
136137
return true
137138
} else {
138-
utils.LogI("Waiting for base secret job result")
139+
logging.LogI("Waiting for base secret job result")
139140
return false
140141
}
141142
}
@@ -213,7 +214,7 @@ func (r *SFController) SetupConfigJob() bool {
213214
// This ensures that the zuul-scheduler loaded the provisionned Zuul config
214215
// for the 'internal' tenant
215216
if needReconfigureTenant {
216-
utils.LogI("Running tenant-reconfigure for the 'internal' tenant")
217+
logging.LogI("Running tenant-reconfigure for the 'internal' tenant")
217218
if r.runZuulInternalTenantReconfigure() {
218219
// Create an empty ConfigMap to keep note the reconfigure has been already done
219220
zsInternalTenantReconfigure.ObjectMeta = metav1.ObjectMeta{

controllers/gateway.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
_ "embed"
1010

1111
"github.com/softwarefactory-project/sf-operator/controllers/libs/base"
12+
"github.com/softwarefactory-project/sf-operator/controllers/libs/logging"
1213
"github.com/softwarefactory-project/sf-operator/controllers/libs/utils"
1314
appsv1 "k8s.io/api/apps/v1"
1415
apiv1 "k8s.io/api/core/v1"
@@ -55,7 +56,7 @@ func (r *SFController) DeployHTTPDGateway() bool {
5556
current := appsv1.Deployment{}
5657
if r.GetM(ident, &current) {
5758
if !utils.MapEquals(&current.Spec.Template.ObjectMeta.Annotations, &annotations) {
58-
utils.LogI("gateway configuration changed, rollout gateway pods ...")
59+
logging.LogI("gateway configuration changed, rollout gateway pods ...")
5960
current.Spec = dep.DeepCopy().Spec
6061
r.UpdateR(&current)
6162
return false

0 commit comments

Comments
 (0)