Skip to content

Commit efecb8e

Browse files
committed
[Maintenance] Extract Debug CLI
1 parent 612699c commit efecb8e

File tree

3 files changed

+104
-37
lines changed

3 files changed

+104
-37
lines changed

cmd/cmd.go

+19-29
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ const (
7575
defaultServerPort = 8528
7676
defaultAPIHTTPPort = 8628
7777
defaultAPIGRPCPort = 8728
78-
defaultLogLevel = "info"
7978
defaultAdminSecretName = "arangodb-operator-dashboard"
8079
defaultAPIJWTSecretName = "arangodb-operator-api-jwt"
8180
defaultAPIJWTKeySecretName = "arangodb-operator-api-jwt-key"
@@ -96,9 +95,6 @@ var (
9695
hardLimit uint64
9796
}
9897

99-
logFormat string
100-
logLevels []string
101-
logSampling bool
10298
serverOptions struct {
10399
host string
104100
port int
@@ -195,9 +191,6 @@ func init() {
195191
f.StringVar(&serverOptions.tlsSecretName, "server.tls-secret-name", "", "Name of secret containing tls.crt & tls.key for HTTPS server (if empty, self-signed certificate is used)")
196192
f.StringVar(&serverOptions.adminSecretName, "server.admin-secret-name", defaultAdminSecretName, "Name of secret containing username + password for login to the dashboard")
197193
f.BoolVar(&serverOptions.allowAnonymous, "server.allow-anonymous-access", false, "Allow anonymous access to the dashboard")
198-
f.StringVar(&logFormat, "log.format", "pretty", "Set log format. Allowed values: 'pretty', 'JSON'. If empty, default format is used")
199-
f.StringArrayVar(&logLevels, "log.level", []string{defaultLogLevel}, fmt.Sprintf("Set log levels in format <level> or <logger>=<level>. Possible loggers: %s", strings.Join(logging.Global().Names(), ", ")))
200-
f.BoolVar(&logSampling, "log.sampling", true, "If true, operator will try to minimize duplication of logging events")
201194
f.BoolVar(&apiOptions.enabled, "api.enabled", true, "Enable operator HTTP and gRPC API")
202195
f.IntVar(&apiOptions.httpPort, "api.http-port", defaultAPIHTTPPort, "HTTP API port to listen on")
203196
f.IntVar(&apiOptions.grpcPort, "api.grpc-port", defaultAPIGRPCPort, "gRPC API port to listen on")
@@ -247,6 +240,9 @@ func init() {
247240
f.StringArrayVar(&metricsOptions.excludedMetricPrefixes, "metrics.excluded-prefixes", nil, "List of the excluded metrics prefixes")
248241
f.BoolVar(&operatorImageDiscovery.defaultStatusDiscovery, "image.discovery.status", true, "Discover Operator Image from Pod Status by default. When disabled Pod Spec is used.")
249242
f.DurationVar(&operatorImageDiscovery.timeout, "image.discovery.timeout", time.Minute, "Timeout for image discovery process")
243+
if err := logging.Init(&cmdMain); err != nil {
244+
panic(err.Error())
245+
}
250246
if err := features.Init(&cmdMain); err != nil {
251247
panic(err.Error())
252248
}
@@ -308,24 +304,10 @@ func executeMain(cmd *cobra.Command, args []string) {
308304
kclient.SetDefaultBurst(operatorKubernetesOptions.burst)
309305

310306
// Prepare log service
311-
var err error
312-
313-
levels, err := logging.ParseLogLevelsFromArgs(logLevels)
314-
if err != nil {
315-
logger.Err(err).Fatal("Unable to parse log level")
307+
if err := logging.Enable(); err != nil {
308+
logger.Err(err).Fatal("Unable to enable logger")
316309
}
317310

318-
// Set root logger to stdout (JSON formatted) if not prettified
319-
if strings.ToUpper(logFormat) == "JSON" {
320-
logging.Global().SetRoot(zerolog.New(os.Stdout).With().Timestamp().Logger())
321-
} else if strings.ToLower(logFormat) != "pretty" && logFormat != "" {
322-
logger.Fatal("Unknown log format: %s", logFormat)
323-
}
324-
logging.Global().Configure(logging.Config{
325-
Levels: levels,
326-
Sampling: logSampling,
327-
})
328-
329311
podNameParts := strings.Split(name, "-")
330312
operatorID := podNameParts[len(podNameParts)-1]
331313

@@ -347,16 +329,16 @@ func executeMain(cmd *cobra.Command, args []string) {
347329
!operatorOptions.enableBackup && !operatorOptions.enableApps && !operatorOptions.enableK2KClusterSync && !operatorOptions.enableML {
348330
if !operatorOptions.versionOnly {
349331
if version.GetVersionV1().IsEnterprise() {
350-
logger.Err(err).Fatal("Turn on --operator.deployment, --operator.deployment-replication, --operator.storage, --operator.backup, --operator.apps, --operator.k2k-cluster-sync, --operator.ml or any combination of these")
332+
logger.Fatal("Turn on --operator.deployment, --operator.deployment-replication, --operator.storage, --operator.backup, --operator.apps, --operator.k2k-cluster-sync, --operator.ml or any combination of these")
351333
} else {
352-
logger.Err(err).Fatal("Turn on --operator.deployment, --operator.deployment-replication, --operator.storage, --operator.backup, --operator.apps, --operator.k2k-cluster-sync or any combination of these")
334+
logger.Fatal("Turn on --operator.deployment, --operator.deployment-replication, --operator.storage, --operator.backup, --operator.apps, --operator.k2k-cluster-sync or any combination of these")
353335
}
354336
}
355337
} else if operatorOptions.versionOnly {
356-
logger.Err(err).Fatal("Options --operator.deployment, --operator.deployment-replication, --operator.storage, --operator.backup, --operator.apps, --operator.k2k-cluster-sync, --operator.ml cannot be enabled together with --operator.version")
338+
logger.Fatal("Options --operator.deployment, --operator.deployment-replication, --operator.storage, --operator.backup, --operator.apps, --operator.k2k-cluster-sync, --operator.ml cannot be enabled together with --operator.version")
357339
} else if !version.GetVersionV1().IsEnterprise() {
358340
if operatorOptions.enableML {
359-
logger.Err(err).Fatal("Options --operator.ml can be enabled only on the Enterprise Operator")
341+
logger.Fatal("Options --operator.ml can be enabled only on the Enterprise Operator")
360342
}
361343
}
362344

@@ -444,7 +426,11 @@ func executeMain(cmd *cobra.Command, args []string) {
444426
if err != nil {
445427
logger.Err(err).Fatal("Failed to create API server")
446428
}
447-
go errors.LogError(logger, "while running API server", apiServer.Run)
429+
go func() {
430+
if err := apiServer.Run(); err != nil {
431+
logger.Err(err).Error("while running API server")
432+
}
433+
}()
448434
}
449435

450436
listenAddr := net.JoinHostPort(serverOptions.host, strconv.Itoa(serverOptions.port))
@@ -493,7 +479,11 @@ func executeMain(cmd *cobra.Command, args []string) {
493479
}); err != nil {
494480
logger.Err(err).Fatal("Failed to create HTTP server")
495481
} else {
496-
go errors.LogError(logger, "error while starting server", svr.Run)
482+
go func() {
483+
if err := svr.Run(); err != nil {
484+
logger.Err(err).Error("error while starting server")
485+
}
486+
}()
497487
}
498488

499489
// startChaos(context.Background(), cfg.KubeCli, cfg.Namespace, chaosLevel)

pkg/logging/cli.go

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
//
2+
// DISCLAIMER
3+
//
4+
// Copyright 2024 ArangoDB GmbH, Cologne, Germany
5+
//
6+
// Licensed under the Apache License, Version 2.0 (the "License");
7+
// you may not use this file except in compliance with the License.
8+
// You may obtain a copy of the License at
9+
//
10+
// http://www.apache.org/licenses/LICENSE-2.0
11+
//
12+
// Unless required by applicable law or agreed to in writing, software
13+
// distributed under the License is distributed on an "AS IS" BASIS,
14+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
// See the License for the specific language governing permissions and
16+
// limitations under the License.
17+
//
18+
// Copyright holder is ArangoDB GmbH, Cologne, Germany
19+
//
20+
21+
package logging
22+
23+
import (
24+
"fmt"
25+
"os"
26+
"strings"
27+
"sync"
28+
29+
"github.com/rs/zerolog"
30+
"github.com/spf13/cobra"
31+
32+
"github.com/arangodb/kube-arangodb/pkg/util/errors"
33+
)
34+
35+
const (
36+
defaultLogLevel = "info"
37+
)
38+
39+
var (
40+
enableLock sync.Mutex
41+
enabled bool
42+
43+
cli struct {
44+
format string
45+
levels []string
46+
sampling bool
47+
}
48+
)
49+
50+
func Init(cmd *cobra.Command) error {
51+
f := cmd.PersistentFlags()
52+
53+
f.StringVar(&cli.format, "log.format", "pretty", "Set log format. Allowed values: 'pretty', 'JSON'. If empty, default format is used")
54+
f.StringArrayVar(&cli.levels, "log.level", []string{defaultLogLevel}, fmt.Sprintf("Set log levels in format <level> or <logger>=<level>. Possible loggers: %s", strings.Join(Global().Names(), ", ")))
55+
f.BoolVar(&cli.sampling, "log.sampling", true, "If true, operator will try to minimize duplication of logging events")
56+
57+
return nil
58+
}
59+
60+
func Enable() error {
61+
enableLock.Lock()
62+
defer enableLock.Unlock()
63+
64+
if enabled {
65+
return errors.Errorf("Logger already enabled")
66+
}
67+
68+
levels, err := ParseLogLevelsFromArgs(cli.levels)
69+
if err != nil {
70+
return errors.WithMessagef(err, "Unable to parse levels")
71+
}
72+
73+
// Set root logger to stdout (JSON formatted) if not prettified
74+
if strings.ToUpper(cli.format) == "JSON" {
75+
Global().SetRoot(zerolog.New(os.Stdout).With().Timestamp().Logger())
76+
} else if strings.ToLower(cli.format) != "pretty" && cli.format != "" {
77+
return errors.Errorf("Unknown log format: %s", cli.format)
78+
}
79+
Global().Configure(Config{
80+
Levels: levels,
81+
Sampling: cli.sampling,
82+
})
83+
84+
return nil
85+
}

pkg/util/errors/errors.go

-8
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,6 @@ import (
3131
"github.com/pkg/errors"
3232

3333
driver "github.com/arangodb/go-driver"
34-
35-
"github.com/arangodb/kube-arangodb/pkg/logging"
3634
)
3735

3836
func Cause(err error) error {
@@ -209,12 +207,6 @@ func libCause(err error) (bool, error) {
209207
}
210208
}
211209

212-
func LogError(logger logging.Logger, msg string, f func() error) {
213-
if err := f(); err != nil {
214-
logger.Err(err).Error(msg)
215-
}
216-
}
217-
218210
type Causer interface {
219211
Cause() error
220212
}

0 commit comments

Comments
 (0)