Skip to content

Commit

Permalink
replace logrus with slog
Browse files Browse the repository at this point in the history
  • Loading branch information
aflanagan committed Jan 16, 2025
1 parent ea333bb commit 2e632dd
Show file tree
Hide file tree
Showing 12 changed files with 208 additions and 144 deletions.
25 changes: 15 additions & 10 deletions cmd/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@ package cmd
import (
"errors"
"fmt"
"log/slog"
"os"
"os/signal"
"syscall"

"github.com/Masterminds/semver"
"github.com/cronitorio/cronitor-kubernetes/pkg"
"github.com/cronitorio/cronitor-kubernetes/pkg/api"
"github.com/cronitorio/cronitor-kubernetes/pkg/collector"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"os"
"os/signal"
"syscall"
)

var dryRun bool
Expand All @@ -32,22 +33,26 @@ func checkVersion() {

currentVersion, err := semver.NewVersion(viperVersion)
if err != nil {
log.Errorf("Error parsing version from viper %s: %v", viperVersion, err)
slog.Error("error parsing version from viper",
"version", viperVersion,
"error", err)
return
}
latestVersion := pkg.GetLatestVersion()
if latestVersion == "" {
log.Errorf("Couldn't get version: %s", currentVersion)
slog.Error("couldn't get version", "current_version", currentVersion)
return
}
latestAvailableVersion, err := semver.NewVersion(latestVersion)
if err != nil {
log.Errorf("Error parsing latest available version %s: %v", latestVersion, err)
slog.Error("error parsing latest available version",
"version", latestVersion,
"error", err)
return
}
constraint, err := semver.NewConstraint("> " + currentVersion.String())
if err != nil {
log.Errorf("Error parsing version constraint: %s", err)
slog.Error("error parsing version constraint", "error", err)
return
}
if constraint.Check(latestAvailableVersion) {
Expand All @@ -71,7 +76,7 @@ func agentRun(cmd *cobra.Command, args []string) error {
cronitorApi := api.NewCronitorApi(apiKey, viper.GetBool("dryrun"))
kubeconfig := viper.GetString("kubeconfig")
if kubeconfig == "" {
log.Info("no kubeconfig provided, defaulting to in-cluster...")
slog.Info("no kubeconfig provided, defaulting to in-cluster...")
}
namespace := viper.GetString("namespace")
collection, err := collector.NewCronJobCollection(kubeconfig, namespace, &cronitorApi)
Expand All @@ -91,7 +96,7 @@ func agentRun(cmd *cobra.Command, args []string) error {
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
select {
case sig := <-c:
log.Infof("Received signal %s to exit", sig.String())
slog.Info("received signal to exit", "signal", sig.String())
gracefulExit()
}
// case <-leaderlost
Expand Down
35 changes: 24 additions & 11 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ package cmd
import (
"errors"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"log/slog"
"os"
"regexp"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var RootCmd = &cobra.Command{
Expand All @@ -26,7 +27,7 @@ func init() {
RootCmd.PersistentFlags().String("kubeconfig", "", "path to a kubeconfig to use")
RootCmd.PersistentFlags().String("apikey", "", "Cronitor.io API key")
RootCmd.PersistentFlags().String("hostname-override", "", "App hostname to use (mainly for testing)")
RootCmd.PersistentFlags().String("log-level", "", "Minimum log level to print for the agent (TRACE, DEBUG, INFO, WARN, ERROR)")
RootCmd.PersistentFlags().String("log-level", "", "Minimum log level to print for the agent (DEBUG, INFO, WARN, ERROR)")
_ = RootCmd.PersistentFlags().MarkHidden("hostname-override")
RootCmd.PersistentFlags().Bool("dev", false, "Set the CLI to dev mode (for things like logs, etc.)")
_ = RootCmd.PersistentFlags().MarkHidden("dev")
Expand All @@ -43,23 +44,35 @@ func initializeConfig(cmd *cobra.Command, args []string) error {
_ = viper.BindPFlag("apikey", cmd.Flags().Lookup("apikey"))
apiKey := viper.GetString("apikey")


if apiKey == "<api key>" {
message := "A valid api key is required. You used the string '<api key>' as the api key, which is invalid"
log.Error(message)
slog.Error(message)
return errors.New(message)
} else if matched, _ := regexp.MatchString(`[\w0-9]+`, apiKey); !matched {
message := "you have provided an invalid API key. Cronitor API keys are comprised only of number and letter characters"
log.Error(message)
slog.Error(message)
return errors.New(message)
}

if logLevel := viper.GetString("log-level"); logLevel != "" {
level, err := log.ParseLevel(logLevel)
if err != nil {
return err
var level slog.Level
switch logLevel {
case "DEBUG":
level = slog.LevelDebug
case "INFO":
level = slog.LevelInfo
case "WARN":
level = slog.LevelWarn
case "ERROR":
level = slog.LevelError
default:
return fmt.Errorf("invalid log level: %s", logLevel)
}
log.SetLevel(level)

handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
})
slog.SetDefault(slog.New(handler))
}

return nil
Expand Down
28 changes: 23 additions & 5 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,37 @@ package cmd
import (
"bytes"
"fmt"
log "github.com/sirupsen/logrus"
"log/slog"
"os"
"strings"
"testing"
)

func TestLogLevelParsing(t *testing.T) {
levelsToTest := []string{"trace", "TRACE", "debug", "DEBUG", "info", "INFO", "warn", "WARN", "warning", "error", "ERROR"}
for _, levelString := range levelsToTest {
t.Run(fmt.Sprintf("test '%s' level", levelString), func(t *testing.T) {
_, err := log.ParseLevel(levelString)
levelsToTest := []struct {
levelString string
level slog.Level
}{
{"debug", slog.LevelDebug},
{"DEBUG", slog.LevelDebug},
{"info", slog.LevelInfo},
{"INFO", slog.LevelInfo},
{"warn", slog.LevelWarn},
{"WARN", slog.LevelWarn},
{"error", slog.LevelError},
{"ERROR", slog.LevelError},
}

for _, tt := range levelsToTest {
t.Run(fmt.Sprintf("test '%s' level", tt.levelString), func(t *testing.T) {
level := new(slog.Level)
err := level.UnmarshalText([]byte(strings.ToUpper(tt.levelString)))
if err != nil {
t.Error(err)
}
if *level != tt.level {
t.Errorf("expected level %v, got %v", tt.level, *level)
}
})
}
}
Expand Down
26 changes: 13 additions & 13 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
package main

import (
"github.com/cronitorio/cronitor-kubernetes/cmd"
"github.com/getsentry/sentry-go"
log "github.com/sirupsen/logrus"
"log/slog"
"os"
"time"

"github.com/cronitorio/cronitor-kubernetes/cmd"
"github.com/getsentry/sentry-go"
)

func init() {
//log.SetLevel(log.DebugLevel)
// Set to true to see line number information
//log.SetReportCaller(false)

formatter := &log.TextFormatter{
FullTimestamp: true,
}
log.SetFormatter(formatter)
// Configure slog with JSON handler (or TextHandler if you prefer)
handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
AddSource: false,
})
slog.SetDefault(slog.New(handler))
}

func main() {
if os.Getenv("SENTRY_ENABLED") == "true" {
log.Info("Enabling Sentry instrumentation...")
slog.Info("Enabling Sentry instrumentation...")
err := sentry.Init(sentry.ClientOptions{
Dsn: "https://[email protected]/6031178",
AttachStacktrace: true,
})
if err != nil {
log.Fatalf("sentry.Init: %s", err)
slog.Error("sentry initialization failed", "error", err)
os.Exit(1)
}
defer sentry.Flush(2 * time.Second)
defer sentry.Recover()
Expand Down
4 changes: 2 additions & 2 deletions pkg/api/constructor.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package api
import (
"bytes"
"fmt"
log "github.com/sirupsen/logrus"
"io/ioutil"
"log/slog"
"net/http"
"os"
)
Expand All @@ -25,7 +25,7 @@ type CronitorApiError struct {
func (c CronitorApiError) ResponseBody() ([]byte, error) {
contents, err := ioutil.ReadAll(c.Response.Body)
if err != nil {
log.Errorf("could not read response body: %v", err)
slog.Error("could not read response body", "error", err)
return []byte{}, err
}
defer c.Response.Body.Close()
Expand Down
17 changes: 10 additions & 7 deletions pkg/api/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import (
"compress/gzip"
"encoding/json"
"fmt"
"github.com/cronitorio/cronitor-kubernetes/pkg"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"io/ioutil"
"log/slog"
"net/http"
"time"

"github.com/cronitorio/cronitor-kubernetes/pkg"
"github.com/pkg/errors"
"github.com/spf13/viper"
)

/*
Expand All @@ -36,10 +37,12 @@ func gzipLogData(logData string) *bytes.Buffer {

gz := gzip.NewWriter(&b)
if _, err := gz.Write([]byte(logData)); err != nil {
log.Fatal(errors.Wrap(err, "error writing gzip"))
slog.Error("error writing gzip", "error", err)
panic(err)
}
if err := gz.Close(); err != nil {
log.Fatal(errors.Wrap(err, "error closing gzip"))
slog.Error("error closing gzip", "error", err)
panic(err)
}
return &b
}
Expand Down Expand Up @@ -109,6 +112,6 @@ func (api CronitorApi) ShipLogData(params *TelemetryEvent) ([]byte, error) {
return nil, err
}
defer response2.Body.Close()
log.Infof("logs shipped for series %s", *params.Series)
slog.Info("logs shipped", "series", *params.Series)
return body, nil
}
19 changes: 9 additions & 10 deletions pkg/api/monitors.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import (
"bytes"
"encoding/json"
"fmt"
"github.com/cronitorio/cronitor-cli/lib"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"io/ioutil"
v1 "k8s.io/api/batch/v1"
"log/slog"
"net/http"
"strings"
"time"

"github.com/cronitorio/cronitor-cli/lib"
"github.com/spf13/viper"
v1 "k8s.io/api/batch/v1"
)

func (api CronitorApi) mainApiUrl() string {
Expand Down Expand Up @@ -47,7 +48,9 @@ func (api CronitorApi) PutCronJobs(cronJobs []*v1.CronJob) ([]*lib.Monitor, erro
return nil, err
}

log.Debugf("request: <%s> %s", url, jsonBytes)
slog.Debug("sending request",
"url", url,
"body", string(jsonBytes))

if api.DryRun {
return make([]*lib.Monitor, 0), nil
Expand All @@ -58,15 +61,13 @@ func (api CronitorApi) PutCronJobs(cronJobs []*v1.CronJob) ([]*lib.Monitor, erro
return nil, err
}

log.Debugf("response: %s", response)
slog.Debug("received response", "response", string(response))

var responseMonitors []*lib.Monitor
if err = json.Unmarshal(response, &responseMonitors); err != nil {
return nil, fmt.Errorf("error from %s: %s, error: %s", url, response, err.Error())
}

// Do we actually need to do anything with the response yet?

return responseMonitors, nil
}

Expand All @@ -83,8 +84,6 @@ func (api CronitorApi) sendHttpRequest(method string, url string, body string) (
request.Header.Add("User-Agent", api.UserAgent)
request.Header.Add("Cronitor-Version", "2020-10-27")

//log.Debug(formatRequest(request))

response, err := client.Do(request)
if err != nil {
return nil, CronitorApiError{err, response}
Expand Down
Loading

0 comments on commit 2e632dd

Please sign in to comment.