Skip to content

Commit

Permalink
[DRAFT] Replace zerolog with slog
Browse files Browse the repository at this point in the history
Signed-off-by: Abhi Kapoor <[email protected]>
  • Loading branch information
abhi-kapoor committed Sep 30, 2024
1 parent dd1ca0f commit f6f6166
Show file tree
Hide file tree
Showing 10 changed files with 154 additions and 83 deletions.
4 changes: 2 additions & 2 deletions cmd/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package cmd
import (
"context"
"fmt"
"log/slog"

"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/zapier/kubechecks/pkg/app_watcher"
"github.com/zapier/kubechecks/pkg/appdir"
"github.com/zapier/kubechecks/pkg/argo_client"
Expand Down Expand Up @@ -94,7 +94,7 @@ func newContainer(ctx context.Context, cfg config.ServerConfig, watchApps bool)
go ctr.ApplicationSetWatcher.Run(ctx)
}
} else {
log.Info().Msgf("not monitoring applications, MonitorAllApplications: %+v", cfg.MonitorAllApplications)
slog.Info(fmt.Sprintf("not monitoring applications, MonitorAllApplications: %+v", cfg.MonitorAllApplications))
}

return ctr, nil
Expand Down
39 changes: 20 additions & 19 deletions cmd/controller_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ package cmd

import (
"context"
"log/slog"
"os"
"os/signal"
"syscall"
"time"

_ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"

Expand All @@ -30,52 +30,53 @@ var ControllerCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()

log.Info().
Str("git-tag", pkg.GitTag).
Str("git-commit", pkg.GitCommit).
Msg("Starting KubeChecks")
slog.Log(ctx, slog.LevelInfo, "Starting KubeChecks",
"git-tag", pkg.GitTag,
"git-commit", pkg.GitCommit,
)

log.Info().Msg("parsing configuration")
slog.Info("parse configuration")
cfg, err := config.New()
if err != nil {
log.Fatal().Err(err).Msg("failed to parse configuration")
LogFatal(ctx, "failed to parse configuration", "error", err)
}

ctr, err := newContainer(ctx, cfg, true)
if err != nil {
log.Fatal().Err(err).Msg("failed to create container")
LogFatal(ctx, "failed to create container", "error", err)
}

log.Info().Msg("initializing git settings")
slog.Info("initializing git settings")
if err = initializeGit(ctr); err != nil {
log.Fatal().Err(err).Msg("failed to initialize git settings")
LogFatal(ctx, "failed to initialize git settings", "error", err)
}

if err = processLocations(ctx, ctr, cfg.PoliciesLocation); err != nil {
log.Fatal().Err(err).Msg("failed to process policy locations")
LogFatal(ctx, "failed to process policy locations", "error", err)
}
if err = processLocations(ctx, ctr, cfg.SchemasLocations); err != nil {
log.Fatal().Err(err).Msg("failed to process schema locations")
LogFatal(ctx, "failed to process schema locations", "error", err)
}

processors, err := getProcessors(ctr)
if err != nil {
log.Fatal().Err(err).Msg("failed to create processors")
LogFatal(ctx, "failed to create processors", "error", err)
}

t, err := initTelemetry(ctx, cfg)
if err != nil {
log.Panic().Err(err).Msg("Failed to initialize telemetry")
slog.Error("failed to initialize telemetry", "error", err)
panic(err)
}
defer t.Shutdown()

log.Info().Msgf("starting web server")
slog.Info("starting app watcher")
startWebserver(ctx, ctr, processors)

log.Info().Msgf("listening for requests")
slog.Info("listening for requests")
waitForShutdown()

log.Info().Msg("shutting down gracefully")
slog.Info("shutting down gracefully")
waitForPendingRequest()
},
}
Expand All @@ -102,7 +103,7 @@ func initializeGit(ctr container.Container) error {

func waitForPendingRequest() {
for events.GetInFlight() > 0 {
log.Info().Int("count", events.GetInFlight()).Msg("waiting for in-flight requests to complete")
slog.Info("waiting for in-flight requests to complete", "count", events.GetInFlight())
time.Sleep(time.Second * 3)
}
}
Expand All @@ -116,7 +117,7 @@ func waitForShutdown() {

go func() {
sig := <-sigs
log.Debug().Str("signal", sig.String()).Msg("received signal")
slog.Debug("received signal", "signal", sig.String())
done <- true
}()

Expand Down
13 changes: 7 additions & 6 deletions cmd/locations.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ package cmd

import (
"context"
"log/slog"
"net/url"
"path/filepath"
"regexp"
"strings"
"time"

"github.com/pkg/errors"
"github.com/rs/zerolog/log"

"github.com/zapier/kubechecks/pkg"
"github.com/zapier/kubechecks/pkg/container"
Expand Down Expand Up @@ -65,11 +65,12 @@ func maybeCloneGitUrl(ctx context.Context, repoManager cloner, repoRefreshDurati
}

if err := repo.Update(ctx); err != nil {
log.Warn().
Err(err).
Str("path", repo.Directory).
Str("url", repo.CloneURL).
Msg("failed to update repo")
slog.Warn(
"failed to update repo",
"error", err,
"path", repo.Directory,
"url", repo.CloneURL,
)
}
}
}()
Expand Down
15 changes: 8 additions & 7 deletions cmd/process.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package cmd

import (
"github.com/rs/zerolog/log"
"log/slog"

"github.com/spf13/cobra"

"github.com/zapier/kubechecks/pkg/config"
Expand All @@ -17,28 +18,28 @@ var processCmd = &cobra.Command{

cfg, err := config.New()
if err != nil {
log.Fatal().Err(err).Msg("failed to generate config")
LogFatal(ctx, "failed to generate config", "error", err)
}

ctr, err := newContainer(ctx, cfg, false)
if err != nil {
log.Fatal().Err(err).Msg("failed to create container")
LogFatal(ctx, "failed to create container", "error", err)
}

log.Info().Msg("initializing git settings")
slog.Info("initializing git settings")
if err = initializeGit(ctr); err != nil {
log.Fatal().Err(err).Msg("failed to initialize git settings")
LogFatal(ctx, "failed to initialize git settings", "error", err)
}

repo, err := ctr.VcsClient.LoadHook(ctx, args[0])
if err != nil {
log.Fatal().Err(err).Msg("failed to load hook")
LogFatal(ctx, "failed to load hook", "error", err)
return
}

processors, err := getProcessors(ctr)
if err != nil {
log.Fatal().Err(err).Msg("failed to create processors")
LogFatal(ctx, "failed to create processors", "error", err)
}

server.ProcessCheckEvent(ctx, repo, ctr, processors)
Expand Down
94 changes: 73 additions & 21 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package cmd

import (
"context"
"log/slog"
"os"
"strings"

"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand All @@ -29,6 +29,20 @@ const envPrefix = "kubechecks"

var envKeyReplacer = strings.NewReplacer("-", "_")

const (
LevelTrace = slog.Level(-8)
LevelFatal = slog.Level(12)
)

var LevelNames = map[slog.Level]string{
slog.LevelError: "ERROR",
slog.LevelWarn: "WARN",
slog.LevelInfo: "INFO",
slog.LevelDebug: "DEBUG",
LevelTrace: "TRACE",
LevelFatal: "FATAL",
}

func init() {
// allows environment variables to use _ instead of -
viper.SetEnvKeyReplacer(envKeyReplacer) // sync-provider becomes SYNC_PROVIDER
Expand All @@ -39,13 +53,15 @@ func init() {
stringFlag(flags, "log-level", "Set the log output level.",
newStringOpts().
withChoices(
zerolog.LevelErrorValue,
zerolog.LevelWarnValue,
zerolog.LevelInfoValue,
zerolog.LevelDebugValue,
zerolog.LevelTraceValue,
func() []string {
values := make([]string, 0, len(LevelNames))
for _, value := range LevelNames {
values = append(values, value)
}
return values
}()...,
).
withDefault("info").
withDefault("INFO").
withShortHand("l"),
)
boolFlag(flags, "persist-log-level", "Persists the set log level down to other module loggers.")
Expand Down Expand Up @@ -115,30 +131,66 @@ func init() {
}

func setupLogOutput() {
output := zerolog.ConsoleWriter{Out: os.Stdout}
log.Logger = log.Output(output)

// Default level is info, unless debug flag is present
levelFlag := viper.GetString("log-level")
level, _ := zerolog.ParseLevel(levelFlag)
ctx := context.Background()
logLevel := &slog.LevelVar{} // INFO
opts := &slog.HandlerOptions{
Level: logLevel,
// Map custom log levels to their string representation
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.LevelKey {
level := a.Value.Any().(slog.Level)
levelLabel, exists := LevelNames[level]
if !exists {
levelLabel = level.String()
}

a.Value = slog.StringValue(levelLabel)
}

return a
},
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, opts))

// Retrieve log level from viper
levelFlag := strings.ToUpper(viper.GetString("log-level"))
level, err := ParseLevel(levelFlag)
if err != nil {
logLevel.Set(level)
} else {
logLevel.Set(slog.LevelInfo)
}

zerolog.SetGlobalLevel(level)
log.Debug().Msg("Debug level logging enabled.")
log.Trace().Msg("Trace level logging enabled.")
log.Info().Msg("Initialized logger.")
slog.SetDefault(logger)
logger.Debug("Debug level logging enabled.")
logger.Log(ctx, LevelTrace, "Trace level logging enabled.")
logger.Info("Initialized logger.")

// set logrus log level to overwrite the logs exporting from argo-cd package
logrusLevel := logrus.ErrorLevel
if viper.GetBool("persist_log_level") {
if log.Debug().Enabled() {
if logger.Enabled(ctx, slog.LevelDebug) {
logrusLevel = logrus.DebugLevel
}
if log.Trace().Enabled() {
if logger.Enabled(ctx, LevelTrace) {
logrusLevel = logrus.TraceLevel
}
}

logrus.StandardLogger().Level = logrusLevel
log.Info().Str("log_level", logrus.StandardLogger().Level.String()).Msg("setting logrus log level")
logger.Info(
"log_level", logrus.StandardLogger().Level.String(),
"setting logrus log level",
)
}

func ParseLevel(s string) (slog.Level, error) {
var level slog.Level
var err = level.UnmarshalText([]byte(s))
return level, err
}

func LogFatal(ctx context.Context, msg string, keysAndValues ...interface{}) {
slog.Log(ctx, LevelFatal, msg, keysAndValues...)
os.Exit(1)
}
Loading

0 comments on commit f6f6166

Please sign in to comment.