Skip to content

Commit

Permalink
Use zap "with" log handlers for better json formatting (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
seanmcgary authored Jun 19, 2024
2 parents 798d64d + d3ad28e commit 73a322c
Show file tree
Hide file tree
Showing 6 changed files with 28 additions and 31 deletions.
5 changes: 2 additions & 3 deletions cmd/claim.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func runClaimgen(
var rootIndex uint32

if cfg.ClaimTimestamp == "latest" {
l.Sugar().Info("Generating claim based on latest submitted reward")
l.Sugar().Infow("Generating claim based on latest submitted reward")
transactor, err := services.NewTransactor(chainClient, gethcommon.HexToAddress(cfg.RewardsCoordinatorAddress))
if err != nil {
l.Sugar().Errorf("Failed to initialize transactor", zap.Error(err))
Expand All @@ -75,7 +75,7 @@ func runClaimgen(
return nil, err
}
claimDate = time.Unix(int64(latestSubmittedTimestamp), 0).UTC().Format(time.DateOnly)
l.Sugar().Debug("Latest submitted timestamp", zap.String("claimDate", claimDate))
l.Sugar().Debugw("Latest submitted timestamp", zap.String("claimDate", claimDate))

rootCount, err := transactor.GetNumberOfPublishedRoots()
if err != nil {
Expand Down Expand Up @@ -150,7 +150,6 @@ var claimCmd = &cobra.Command{
log.Fatalln(err)
}
defer logger.Sync()
logger.Sugar().Debug(cfg)

solidity, err := runClaimgen(ctx, cfg, logger)

Expand Down
1 change: 0 additions & 1 deletion cmd/distribution.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ var distributionCmd = &cobra.Command{
log.Fatalln(err)
}
defer logger.Sync()
logger.Sugar().Debug(cfg)

res, err := runDistribution(ctx, cfg, logger)

Expand Down
7 changes: 3 additions & 4 deletions cmd/updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,13 @@ func runUpdater(ctx context.Context, cfg *config.UpdaterConfig, logger *zap.Logg

tree, err := u.Update(ctx)
if err != nil {
logger.Sugar().Info("Failed to update", zap.Error(err))
logger.Sugar().Infow("Failed to update", zap.Error(err))
return nil
}
// Since the updater can run on a cron job checking for new roots, its possible for it to run and not have any new
// roots to update. This isnt a success or a failure, so we just log it and return nil
if tree != nil {
logger.Sugar().Info("Update successful")
logger.Sugar().Infow("Update successful")
}
return nil
}
Expand Down Expand Up @@ -94,14 +94,13 @@ var updaterCmd = &cobra.Command{
log.Fatalln(err)
}
defer logger.Sync()
logger.Sugar().Debug(cfg)

err = runUpdater(ctx, cfg, logger)
if err != nil {
logger.Sugar().Error(err)
}
if err := s.Close(); err != nil {
logger.Sugar().Error("Failed to close statsd client", zap.Error(err))
logger.Sugar().Errorw("Failed to close statsd client", zap.Error(err))
}
},
}
Expand Down
14 changes: 7 additions & 7 deletions pkg/proofDataFetcher/httpProofDataFetcher/fetcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func (h *HttpProofDataFetcher) FetchClaimAmountsForDate(ctx context.Context, dat
span, ctx := ddTracer.StartSpanFromContext(ctx, "httpProofDataFetcher::FetchClaimAmountsForDate")
defer span.Finish()

h.logger.Sugar().Debug(fmt.Sprintf("Fetching claim amounts for date '%s'", date), zap.String("date", date))
h.logger.Sugar().Debugw(fmt.Sprintf("Fetching claim amounts for date '%s'", date), zap.String("date", date))
fullUrl := h.buildClaimAmountsUrl(date)

rawBody, err := h.handleRequest(ctx, fullUrl)
Expand Down Expand Up @@ -106,7 +106,7 @@ func (h *HttpProofDataFetcher) FetchRecentSnapshotList(ctx context.Context) ([]*

snapshots := make([]*proofDataFetcher.Snapshot, 0)
if err := json.Unmarshal(rawBody, &snapshots); err != nil {
h.logger.Sugar().Error("Failed to unmarshal snapshots", zap.Error(err))
h.logger.Sugar().Errorw("Failed to unmarshal snapshots", zap.Error(err))
return nil, err
}
return snapshots, nil
Expand Down Expand Up @@ -135,13 +135,13 @@ func (h *HttpProofDataFetcher) FetchPostedRewards(ctx context.Context) ([]*proof

rawBody, err := h.handleRequest(ctx, fullUrl)
if err != nil {
h.logger.Sugar().Error("Failed to fetch posted rewards", zap.Error(err))
h.logger.Sugar().Errorw("Failed to fetch posted rewards", zap.Error(err))
return nil, err
}

rewards := make([]*proofDataFetcher.SubmittedRewardRoot, 0)
if err := json.Unmarshal(rawBody, &rewards); err != nil {
h.logger.Sugar().Error("Failed to unmarshal rewards", zap.Error(err))
h.logger.Sugar().Errorw("Failed to unmarshal rewards", zap.Error(err))
return nil, err
}
return rewards, nil
Expand All @@ -153,12 +153,12 @@ func (h *HttpProofDataFetcher) handleRequest(ctx context.Context, fullUrl string

req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullUrl, nil)
if err != nil {
h.logger.Sugar().Error("Failed to form request", zap.Error(err))
h.logger.Sugar().Errorw("Failed to form request", zap.Error(err))
}

res, err := h.Client.Do(req)
if err != nil {
h.logger.Sugar().Error("Request failed", zap.Error(err))
h.logger.Sugar().Errorw("Request failed", zap.Error(err))
return nil, err
}
defer res.Body.Close()
Expand All @@ -173,7 +173,7 @@ func (h *HttpProofDataFetcher) handleRequest(ctx context.Context, fullUrl string

if res.StatusCode >= 400 {
errMsg := fmt.Sprintf("Received error code '%d'", res.StatusCode)
h.logger.Sugar().Error(errMsg,
h.logger.Sugar().Errorw(errMsg,
zap.String("url", fullUrl),
zap.String("body", string(rawBody)),
)
Expand Down
8 changes: 4 additions & 4 deletions pkg/updater/updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func (u *Updater) Update(ctx context.Context) (*merkletree.MerkleTree, error) {
// If most recent snapshot's timestamp is equal to the latest submitted timestamp, then we don't need to update
if lst.Equal(latestSnapshot.SnapshotDate) {
metrics.GetStatsdClient().Incr(metrics.Counter_UpdateNoUpdate, nil, 1)
u.logger.Sugar().Info("latest snapshot is the most recent reward")
u.logger.Sugar().Infow("latest snapshot is the most recent reward")
return nil, nil
}
// If the most recent snapshot timestamp is less than whats already on chain, we have a problem
Expand All @@ -81,13 +81,13 @@ func (u *Updater) Update(ctx context.Context) (*merkletree.MerkleTree, error) {
calculatedUntilTimestamp := latestSnapshot.SnapshotDate.UTC().Unix()

// send the merkle root to the smart contract
u.logger.Sugar().Info("updating rewards", zap.String("new_root", utils.ConvertBytesToString(newRoot)))
u.logger.Sugar().Infow("updating rewards", zap.String("new_root", utils.ConvertBytesToString(newRoot)))

// return rewardsProofData.AccountTree, nil
u.logger.Sugar().Info("Calculated timestamp", zap.Int64("calculated_until_timestamp", calculatedUntilTimestamp))
u.logger.Sugar().Infow("Calculated timestamp", zap.Int64("calculated_until_timestamp", calculatedUntilTimestamp))
if err := u.transactor.SubmitRoot(ctx, [32]byte(newRoot), uint32(calculatedUntilTimestamp)); err != nil {
metrics.GetStatsdClient().Incr(metrics.Counter_UpdateFails, nil, 1)
u.logger.Sugar().Error("Failed to submit root", zap.Error(err))
u.logger.Sugar().Errorw("Failed to submit root", zap.Error(err))
return rewardsProofData.AccountTree, err
} else {
metrics.GetStatsdClient().Incr(metrics.Counter_UpdateSuccess, nil, 1)
Expand Down
24 changes: 12 additions & 12 deletions pkg/validator/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,32 +38,32 @@ func (v *Validator) ValidatePostedRoot(ctx context.Context) (string, bool, error

lst := time.Unix(int64(retrievedRoot.RewardsCalculationEndTimestamp), 0).UTC().Format(time.DateOnly)

v.logger.Sugar().Info(fmt.Sprintf("Retrieved root has timestamp of '%v'", lst))
v.logger.Sugar().Infow(fmt.Sprintf("Retrieved root has timestamp of '%v'", lst))

// Get the data for the latest snapshot and load it into a distribution instance
rewardsProofData, err := v.proofDataFetcher.FetchClaimAmountsForDate(ctx, lst)
if err != nil {
v.logger.Sugar().Error(fmt.Sprintf("Failed to fetch claim amounts for date '%s'", lst), zap.Error(err))
v.logger.Sugar().Errorw(fmt.Sprintf("Failed to fetch claim amounts for date '%s'", lst), zap.Error(err))
return lst, false, err
}

root := rewardsProofData.AccountTree.Root()

if err != nil {
v.logger.Sugar().Error("Failed to get root by index", zap.Error(err))
v.logger.Sugar().Errorw("Failed to get root by index", zap.Error(err))
return lst, false, err
}

postedRoot := hexutil.Encode(retrievedRoot.Root[:])
computedRoot := hexutil.Encode(root[:])

if !cmp.Equal(postedRoot, computedRoot) {
v.logger.Sugar().Error("Roots do not match",
zap.String("postedRoot", postedRoot),
zap.String("computedRoot", computedRoot),
)
return lst, false, nil
}
v.logger.Sugar().Info("Roots match")
return lst, true, nil
matchFound := cmp.Equal(postedRoot, computedRoot)

v.logger.Sugar().Infow("root match result",
zap.Bool("matchFound", matchFound),
zap.String("postedRoot", postedRoot),
zap.String("computedRoot", computedRoot),
)

return lst, matchFound, nil
}

0 comments on commit 73a322c

Please sign in to comment.