Skip to content

Commit

Permalink
chore: replace zerolog with zap
Browse files Browse the repository at this point in the history
  • Loading branch information
gustavogama-cll committed Dec 12, 2024
1 parent 2855b16 commit d276898
Show file tree
Hide file tree
Showing 16 changed files with 259 additions and 384 deletions.
18 changes: 11 additions & 7 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package cmd
import (
"os"

"github.com/rs/zerolog"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.uber.org/zap"

"github.com/smartcontractkit/timelock-worker/pkg/logger"
)
Expand All @@ -15,9 +15,9 @@ var (
Use: "timelock-worker",
Short: "Pull and execute scheduled transactions from Timelock contract",
}

logs *zerolog.Logger
logLevel, output string
logs *zap.Logger
logLevel string
output string
)

func Execute() {
Expand Down Expand Up @@ -53,7 +53,11 @@ func configureRootCmd() error {
}

func initConfig() {
// Output hardcoded to JSON
logs = logger.Logger(viper.GetString("log-level"), viper.GetString("output"))
logs.Debug().Msgf("initialized Logger")
var err error
logs, err = logger.NewLogger(viper.GetString("log-level"), viper.GetString("output"))
if err != nil {
panic("unable to create logger")
}

logs.Debug("initialized Logger")
}
32 changes: 17 additions & 15 deletions cmd/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func startCommand() *cobra.Command {
// Precedence: flags > env variables > timelock.env file.
timelockConf, err := cli.NewTimelockCLI()
if err != nil {
logs.Fatal().Msgf("error initializing configuration: %s", err.Error())
logs.Sugar().Fatalf("error initializing configuration: %s", err.Error())
}
// Set liveStatus to OK on startup.
// Set readyStatus to Error on startup.
Expand All @@ -54,63 +54,65 @@ func startHandler(cmd *cobra.Command, _ []string) {
}

func startTimelock(cmd *cobra.Command) {
slog := logs.Sugar()

nodeURL, err := cmd.Flags().GetString("node-url")
if err != nil {
logs.Fatal().Msgf("value of node-url not set: %s", err.Error())
slog.Fatalf("value of node-url not set: %s", err.Error())
}

timelockAddress, err := cmd.Flags().GetString("timelock-address")
if err != nil {
logs.Fatal().Msgf("value of timelock-address not set: %s", err.Error())
slog.Fatalf("value of timelock-address not set: %s", err.Error())
}

callProxyAddress, err := cmd.Flags().GetString("call-proxy-address")
if err != nil {
logs.Fatal().Msgf("value of call-proxy-address not set: %s", err.Error())
slog.Fatalf("value of call-proxy-address not set: %s", err.Error())
}

privateKey, err := cmd.Flags().GetString("private-key")
if err != nil {
logs.Fatal().Msgf("value of private-key not set: %s", err.Error())
slog.Fatalf("value of private-key not set: %s", err.Error())
}

fromBlock, err := cmd.Flags().GetInt64("from-block")
if err != nil {
logs.Fatal().Msgf("value of from-block not set: %s", err.Error())
slog.Fatalf("value of from-block not set: %s", err.Error())
}

pollPeriod, err := cmd.Flags().GetInt64("poll-period")
if err != nil {
logs.Fatal().Msgf("value of poll-period not set: %s", err.Error())
slog.Fatalf("value of poll-period not set: %s", err.Error())
}

eventListenerPollPeriod, err := cmd.Flags().GetInt64("event-listener-poll-period")
if err != nil {
logs.Fatal().Msgf("value of poll-period not set: %s", err.Error())
slog.Fatalf("value of poll-period not set: %s", err.Error())
}

dryRun, err := cmd.Flags().GetBool("dry-run")
if err != nil {
logs.Fatal().Msgf("value of dry-run not set: %s", err.Error())
slog.Fatalf("value of dry-run not set: %s", err.Error())
}

tWorker, err := timelock.NewTimelockWorker(nodeURL, timelockAddress, callProxyAddress, privateKey,
big.NewInt(fromBlock), pollPeriod, eventListenerPollPeriod, dryRun, logs)
big.NewInt(fromBlock), pollPeriod, eventListenerPollPeriod, dryRun, slog)
if err != nil {
logs.Fatal().Msgf("error creating the timelock-worker: %s", err.Error())
slog.Fatalf("error creating the timelock-worker: %s", err.Error())
}

if err := tWorker.Listen(context.Background()); err != nil {
logs.Fatal().Msgf("error while starting timelock-worker: %s", err.Error())
slog.Fatalf("error while starting timelock-worker: %s", err.Error())
}

logs.Info().Msg("shutting down timelock-worker")
slog.Infof("shutting down timelock-worker")
}

func startHTTPHealthServer() {
timelock.StartHTTPHealthServer(logs)
timelock.StartHTTPHealthServer(logs.Sugar())
}

func startMetricsServer() {
timelock.StartMetricsServer(logs)
timelock.StartMetricsServer(logs.Sugar())
}
2 changes: 1 addition & 1 deletion cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,5 @@ func versionCommand() *cobra.Command {
}

func versionHandler(_ *cobra.Command, _ []string) {
logs.Info().Msgf("%s Version: %s Commit: %s", os.Args[0], Version, Commit)
logs.Sugar().Infof("%s Version: %s Commit: %s", os.Args[0], Version, Commit)
}
5 changes: 2 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ require (
github.com/ethereum/go-ethereum v1.13.15
github.com/google/go-cmp v0.6.0
github.com/prometheus/client_golang v1.19.1
github.com/rs/zerolog v1.33.0
github.com/samber/lo v1.47.0
github.com/smartcontractkit/ccip-owner-contracts v0.0.0-20240917103524-56f1a8d2cd4b
github.com/smartcontractkit/chain-selectors v1.0.17
github.com/spf13/cobra v1.8.1
github.com/spf13/viper v1.19.0
github.com/stretchr/testify v1.9.0
github.com/testcontainers/testcontainers-go v0.34.0
go.uber.org/zap v1.27.0
)

require (
Expand Down Expand Up @@ -129,8 +129,7 @@ require (
go.opentelemetry.io/otel v1.24.0 // indirect
go.opentelemetry.io/otel/metric v1.24.0 // indirect
go.opentelemetry.io/otel/trace v1.24.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/exp v0.0.0-20240808152545-0cdaa3abc0fa // indirect
golang.org/x/net v0.28.0 // indirect
Expand Down
17 changes: 6 additions & 11 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7np
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk=
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA=
github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=
github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
Expand Down Expand Up @@ -157,7 +156,6 @@ github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg78
github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo=
github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw=
github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU=
github.com/gogo/googleapis v0.0.0-20180223154316-0cd9801be74a/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s=
Expand Down Expand Up @@ -273,7 +271,6 @@ github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hd
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
Expand Down Expand Up @@ -365,9 +362,6 @@ github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjR
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo=
github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
Expand Down Expand Up @@ -487,10 +481,12 @@ go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y
go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU=
go.opentelemetry.io/proto/otlp v1.0.0 h1:T0TX0tmXU8a3CbNXzEKGeU5mIVOdf0oykP+u2lIVU/I=
go.opentelemetry.io/proto/otlp v1.0.0/go.mod h1:Sy6pihPLfYHkr3NkUbEhGHFhINUSI/v80hjKIs5JXpM=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
Expand Down Expand Up @@ -568,7 +564,6 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
Expand Down
58 changes: 19 additions & 39 deletions pkg/logger/logger.go
Original file line number Diff line number Diff line change
@@ -1,53 +1,33 @@
package logger

import (
"os"
"sync"
"time"
"fmt"

"github.com/rs/zerolog"
"go.uber.org/zap"
)

var (
once sync.Once //nolint:gochecknoglobals
logger *zerolog.Logger //nolint:gochecknoglobals
)

// humanConsoleWriter configures the human-readable output.
var humanConsoleWriter = zerolog.ConsoleWriter{ //nolint:gochecknoglobals
Out: os.Stdout,
TimeFormat: time.RFC3339,
}
// NewLogger initializes the Logger with the given arguments.
func NewLogger(logLevel string, output string) (*zap.Logger, error) {
var err error
var loggerConfig zap.Config

// Logger returns an instance of Logger.
func Logger(logLevel string, output string) *zerolog.Logger {
if logger == nil {
once.Do(
func() {
logger = newLogger(logLevel, output)
})
switch output {
case "json":
loggerConfig = zap.NewProductionConfig()
case "human":
loggerConfig = zap.NewDevelopmentConfig()
default:
return nil, fmt.Errorf("invalid logger output: %q", output)
}

return logger
}

// newLogger initializes the Logger with the given arguments.
func newLogger(logLevel string, output string) *zerolog.Logger {
level, err := zerolog.ParseLevel(logLevel)
loggerConfig.Level, err = zap.ParseAtomicLevel(logLevel)
if err != nil {
// Do not crash on wrong user input, default to InfoLevel.
level = zerolog.InfoLevel
return nil, err
}

var l zerolog.Logger
switch output {
case "human":
l = zerolog.New(humanConsoleWriter).Level(level).With().Timestamp().Logger()
case "json":
l = zerolog.New(os.Stdout).Level(level).With().Timestamp().Logger()
default:
l = zerolog.New(humanConsoleWriter).Level(level).With().Timestamp().Logger()
}
// use stdout, not stderr to maintain compatibility with zerolog
loggerConfig.OutputPaths = []string{"stdout"}
loggerConfig.ErrorOutputPaths = []string{"stdout"}

return &l
return loggerConfig.Build()
}
95 changes: 48 additions & 47 deletions pkg/logger/logger_test.go
Original file line number Diff line number Diff line change
@@ -1,58 +1,59 @@
package logger_test

import (
"reflect"
"testing"

"github.com/rs/zerolog"
"github.com/stretchr/testify/require"
"go.uber.org/zap"

"github.com/smartcontractkit/timelock-worker/pkg/logger"
"github.com/stretchr/testify/assert"
)

func TestLogger(t *testing.T) {
testLogger := logger.Logger("info", "human")
assert.NotNil(t, testLogger)

testType := reflect.TypeOf(testLogger)
loggerType := reflect.TypeOf((*zerolog.Logger)(nil))

if !(loggerType == testType) {
t.Errorf("testType does not implement loggerType")
func Test_NewLogger(t *testing.T) {
t.Parallel()

tests := []struct {
name string
level string
output string
wantErr string
}{
{
name: "success: info human",
level: "info",
output: "human",
},
{
name: "success: debug json",
level: "info",
output: "json",
},
{
name: "invalid log level",
level: "invalid",
output: "human",
wantErr: "unrecognized level: \"invalid\"",
},
{
name: "invalid output",
level: "info",
output: "invalid",
wantErr: "invalid logger output: \"invalid\"",
},
}
}

func TestLoggerJSON(t *testing.T) {
testLogger := logger.Logger("debug", "json")
assert.NotNil(t, testLogger)

testType := reflect.TypeOf(testLogger)
loggerType := reflect.TypeOf((*zerolog.Logger)(nil))

if !(loggerType == testType) {
t.Errorf("testType does not implement loggerType")
}
}

func TestLoggerWrongLogLevel(t *testing.T) {
testLogger := logger.Logger("wrongLogLevel", "human")
assert.NotNil(t, testLogger)

testType := reflect.TypeOf(testLogger)
loggerType := reflect.TypeOf((*zerolog.Logger)(nil))

if !(loggerType == testType) {
t.Errorf("testType does not implement loggerType")
}
}

func TestLoggerWrongAll(t *testing.T) {
testLogger := logger.Logger("wrongLogLevel", "wrongOutput")
assert.NotNil(t, testLogger)

testType := reflect.TypeOf(testLogger)
loggerType := reflect.TypeOf((*zerolog.Logger)(nil))

if !(loggerType == testType) {
t.Errorf("testType does not implement loggerType")
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()

logger, err := logger.NewLogger(tt.level, tt.output)

if tt.wantErr == "" {
require.NoError(t, err)
require.IsType(t, logger, new(zap.Logger))
} else {
require.ErrorContains(t, err, tt.wantErr)
}
})
}
}
Loading

0 comments on commit d276898

Please sign in to comment.