From 477fdbc0eecb07dc8150741e053996c3b1412cfa Mon Sep 17 00:00:00 2001 From: Matthias Fasching <5011972+fasmat@users.noreply.github.com> Date: Wed, 14 Aug 2024 09:40:25 +0000 Subject: [PATCH] Remove obsolete log package functions (#6252) ## Motivation This is another step in the gradual removal of the `log` package from the node. Many now unused functions were removed. --- bootstrap/types.go | 5 +- common/types/account.go | 6 +- common/types/activation.go | 16 +- common/types/ballot.go | 29 +-- common/types/eligibility.go | 8 +- common/types/poet.go | 10 +- common/types/proposal.go | 15 +- common/types/result/result.go | 11 +- common/types/tortoise_data.go | 6 +- common/types/transaction_header.go | 4 +- common/types/transaction_result.go | 10 +- events/reporter.go | 6 +- fetch/wire_types.go | 6 +- hare3/protocol.go | 3 +- hare3/types.go | 3 +- hare4/protocol.go | 3 +- hare4/types.go | 3 +- log/context_test.go | 8 +- log/log.go | 85 ++----- log/log_mock.go | 359 ----------------------------- log/log_test.go | 69 ++---- log/logtest/log.go | 16 -- log/zap.go | 14 +- node/node.go | 45 ++-- systest/tests/partition_test.go | 6 +- 25 files changed, 133 insertions(+), 613 deletions(-) delete mode 100644 log/log_mock.go diff --git a/bootstrap/types.go b/bootstrap/types.go index 7c4fd4c673..b0dbbc6319 100644 --- a/bootstrap/types.go +++ b/bootstrap/types.go @@ -1,8 +1,9 @@ package bootstrap import ( + "go.uber.org/zap/zapcore" + "github.com/spacemeshos/go-spacemesh/common/types" - "github.com/spacemeshos/go-spacemesh/log" ) type Update struct { @@ -31,7 +32,7 @@ type EpochOverride struct { ActiveSet []types.ATXID } -func (vd *VerifiedUpdate) MarshalLogObject(encoder log.ObjectEncoder) error { +func (vd *VerifiedUpdate) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("persisted", vd.Persisted) encoder.AddString("epoch", vd.Data.Epoch.String()) encoder.AddString("beacon", vd.Data.Beacon.String()) diff --git a/common/types/account.go b/common/types/account.go index c2103b4273..a59266df90 100644 --- a/common/types/account.go +++ b/common/types/account.go @@ -1,8 +1,6 @@ package types -import ( - "github.com/spacemeshos/go-spacemesh/log" -) +import "go.uber.org/zap/zapcore" //go:generate scalegen @@ -17,7 +15,7 @@ type Account struct { } // MarshalLogObject implements encoding for the account state. -func (a *Account) MarshalLogObject(encoder log.ObjectEncoder) error { +func (a *Account) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("layer", a.Layer.String()) encoder.AddString("principal", a.Address.String()) encoder.AddUint64("next nonce", a.NextNonce) diff --git a/common/types/activation.go b/common/types/activation.go index 10a585e80d..703d1ffd4f 100644 --- a/common/types/activation.go +++ b/common/types/activation.go @@ -7,6 +7,7 @@ import ( "github.com/spacemeshos/go-scale" "github.com/spacemeshos/post/shared" + "go.uber.org/zap/zapcore" "github.com/spacemeshos/go-spacemesh/common/util" "github.com/spacemeshos/go-spacemesh/log" @@ -56,9 +57,6 @@ func (t ATXID) Bytes() []byte { return Hash32(t).Bytes() } -// Field returns a log field. Implements the LoggableField interface. -func (t ATXID) Field() log.Field { return log.FieldNamed("atx_id", t.Hash32()) } - // EncodeScale implements scale codec interface. func (t *ATXID) EncodeScale(e *scale.Encoder) (int, error) { return scale.EncodeByteArray(e, t[:]) @@ -83,7 +81,7 @@ var EmptyATXID = ATXID{} type ATXIDs []ATXID // impl zap's ArrayMarshaler interface. -func (ids ATXIDs) MarshalLogArray(enc log.ArrayEncoder) error { +func (ids ATXIDs) MarshalLogArray(enc zapcore.ArrayEncoder) error { for _, id := range ids { enc.AppendString(id.String()) } @@ -107,7 +105,7 @@ type NIPostChallenge struct { InitialPost *Post } -func (c *NIPostChallenge) MarshalLogObject(encoder log.ObjectEncoder) error { +func (c *NIPostChallenge) MarshalLogObject(encoder zapcore.ObjectEncoder) error { if c == nil { return nil } @@ -136,7 +134,7 @@ type ATXMetadata struct { MsgHash Hash32 // Hash of InnerActivationTx (returned by HashInnerBytes) } -func (m *ATXMetadata) MarshalLogObject(encoder log.ObjectEncoder) error { +func (m *ATXMetadata) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddUint32("epoch", uint32(m.PublishEpoch)) encoder.AddString("hash", m.MsgHash.ShortString()) return nil @@ -222,7 +220,7 @@ func (atx *ActivationTx) TickHeight() uint64 { } // MarshalLogObject implements logging interface. -func (atx *ActivationTx) MarshalLogObject(encoder log.ObjectEncoder) error { +func (atx *ActivationTx) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("atx_id", atx.id.String()) encoder.AddString("smesher", atx.SmesherID.String()) encoder.AddUint32("publish_epoch", atx.PublishEpoch.Uint32()) @@ -321,7 +319,7 @@ func (v VRFPostIndex) Field() log.Field { return log.Uint64("vrf_nonce", uint64( // Post is an alias to postShared.Proof. type Post shared.Proof -func (p *Post) MarshalLogObject(encoder log.ObjectEncoder) error { +func (p *Post) MarshalLogObject(encoder zapcore.ObjectEncoder) error { if p == nil { return nil } @@ -337,7 +335,7 @@ type PostMetadata struct { LabelsPerUnit uint64 } -func (m *PostMetadata) MarshalLogObject(encoder log.ObjectEncoder) error { +func (m *PostMetadata) MarshalLogObject(encoder zapcore.ObjectEncoder) error { if m == nil { return nil } diff --git a/common/types/ballot.go b/common/types/ballot.go index c1d41a9f28..71883e59fc 100644 --- a/common/types/ballot.go +++ b/common/types/ballot.go @@ -7,11 +7,11 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/spacemeshos/go-scale" + "go.uber.org/zap/zapcore" "github.com/spacemeshos/go-spacemesh/codec" "github.com/spacemeshos/go-spacemesh/common/util" "github.com/spacemeshos/go-spacemesh/hash" - "github.com/spacemeshos/go-spacemesh/log" ) const ( @@ -103,7 +103,7 @@ type BallotMetadata struct { MsgHash Hash32 // Hash of InnerBallot (returned by HashInnerBytes) } -func (m *BallotMetadata) MarshalLogObject(encoder log.ObjectEncoder) error { +func (m *BallotMetadata) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddUint32("layer", m.Layer.Uint32()) encoder.AddString("msgHash", m.MsgHash.String()) return nil @@ -186,21 +186,21 @@ type Votes struct { } // MarshalLogObject implements logging interface. -func (v *Votes) MarshalLogObject(encoder log.ObjectEncoder) error { +func (v *Votes) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("base", v.Base.String()) - encoder.AddArray("support", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + encoder.AddArray("support", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { for _, vote := range v.Support { encoder.AppendObject(&vote) } return nil })) - encoder.AddArray("against", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + encoder.AddArray("against", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { for _, vote := range v.Against { encoder.AppendObject(&vote) } return nil })) - encoder.AddArray("abstain", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + encoder.AddArray("abstain", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { for _, lid := range v.Abstain { encoder.AppendString(lid.String()) } @@ -216,7 +216,7 @@ type BlockHeader struct { } // MarshalLogObject implements logging interface. -func (header *BlockHeader) MarshalLogObject(encoder log.ObjectEncoder) error { +func (header *BlockHeader) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("id", header.ID.String()) encoder.AddUint32("layer", header.LayerID.Uint32()) encoder.AddUint64("height", header.Height) @@ -234,7 +234,7 @@ type Opinion struct { } // MarshalLogObject implements logging interface. -func (o *Opinion) MarshalLogObject(encoder log.ObjectEncoder) error { +func (o *Opinion) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("hash", o.Hash.ShortString()) return o.Votes.MarshalLogObject(encoder) } @@ -261,24 +261,17 @@ func (b *Ballot) Initialize() error { // SignedBytes returns the serialization of the BallotMetadata for signing. func (b *Ballot) SignedBytes() []byte { - data, err := codec.Encode(&BallotMetadata{ + return codec.MustEncode(&BallotMetadata{ Layer: b.Layer, MsgHash: BytesToHash(b.HashInnerBytes()), }) - if err != nil { - log.With().Fatal("failed to serialize BallotMetadata", log.Err(err)) - } - return data } // HashInnerBytes returns the hash of the InnerBallot. func (b *Ballot) HashInnerBytes() []byte { h := hash.GetHasher() defer hash.PutHasher(h) - _, err := codec.EncodeTo(h, &b.InnerBallot) - if err != nil { - log.With().Fatal("failed to encode InnerBallot for hashing", log.Err(err)) - } + codec.MustEncodeTo(h, &b.InnerBallot) return h.Sum(nil) } @@ -303,7 +296,7 @@ func (b *Ballot) IsMalicious() bool { } // MarshalLogObject implements logging encoder for Ballot. -func (b *Ballot) MarshalLogObject(encoder log.ObjectEncoder) error { +func (b *Ballot) MarshalLogObject(encoder zapcore.ObjectEncoder) error { var ( activeHash Hash32 beacon Beacon diff --git a/common/types/eligibility.go b/common/types/eligibility.go index cca3292b92..505596b530 100644 --- a/common/types/eligibility.go +++ b/common/types/eligibility.go @@ -1,7 +1,7 @@ package types import ( - "github.com/spacemeshos/go-spacemesh/log" + "go.uber.org/zap/zapcore" ) //go:generate scalegen @@ -22,7 +22,7 @@ type HareEligibilityGossip struct { Eligibility HareEligibility } -func (hg *HareEligibilityGossip) MarshalLogObject(encoder log.ObjectEncoder) error { +func (hg *HareEligibilityGossip) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddUint32("layer", hg.Layer.Uint32()) encoder.AddUint32("round", hg.Round) encoder.AddString("smesher", hg.NodeID.String()) @@ -41,7 +41,7 @@ type HareEligibility struct { } // MarshalLogObject implements logging interface. -func (e *HareEligibility) MarshalLogObject(encoder log.ObjectEncoder) error { +func (e *HareEligibility) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddUint16("count", e.Count) encoder.AddString("proof", e.Proof.String()) return nil @@ -59,7 +59,7 @@ type VotingEligibility struct { } // MarshalLogObject implements logging interface. -func (v *VotingEligibility) MarshalLogObject(encoder log.ObjectEncoder) error { +func (v *VotingEligibility) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddUint32("j", v.J) encoder.AddString("sig", v.Sig.String()) return nil diff --git a/common/types/poet.go b/common/types/poet.go index f04b613517..89a62113ea 100644 --- a/common/types/poet.go +++ b/common/types/poet.go @@ -7,9 +7,9 @@ import ( "time" poetShared "github.com/spacemeshos/poet/shared" + "go.uber.org/zap/zapcore" "github.com/spacemeshos/go-spacemesh/codec" - "github.com/spacemeshos/go-spacemesh/log" ) //go:generate scalegen -types PoetProof,PoetProofMessage @@ -35,20 +35,20 @@ type PoetProof struct { LeafCount uint64 } -func (p *PoetProof) MarshalLogObject(encoder log.ObjectEncoder) error { +func (p *PoetProof) MarshalLogObject(encoder zapcore.ObjectEncoder) error { if p == nil { return nil } encoder.AddUint64("LeafCount", p.LeafCount) encoder.AddString("MerkleProof.Root", hex.EncodeToString(p.Root)) - encoder.AddArray("MerkleProof.ProvenLeaves", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + encoder.AddArray("MerkleProof.ProvenLeaves", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { for _, v := range p.ProvenLeaves { encoder.AppendString(hex.EncodeToString(v)) } return nil })) - encoder.AddArray("MerkleProof.ProofNodes", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + encoder.AddArray("MerkleProof.ProofNodes", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { for _, v := range p.ProofNodes { encoder.AppendString(hex.EncodeToString(v)) } @@ -70,7 +70,7 @@ type PoetProofMessage struct { Signature EdSignature } -func (p *PoetProofMessage) MarshalLogObject(encoder log.ObjectEncoder) error { +func (p *PoetProofMessage) MarshalLogObject(encoder zapcore.ObjectEncoder) error { if p == nil { return nil } diff --git a/common/types/proposal.go b/common/types/proposal.go index f29d39d423..ae7aea7aab 100644 --- a/common/types/proposal.go +++ b/common/types/proposal.go @@ -7,10 +7,10 @@ import ( "github.com/google/go-cmp/cmp" "github.com/spacemeshos/go-scale" + "go.uber.org/zap/zapcore" "github.com/spacemeshos/go-spacemesh/codec" "github.com/spacemeshos/go-spacemesh/hash" - "github.com/spacemeshos/go-spacemesh/log" ) const ( @@ -107,24 +107,17 @@ func (p *Proposal) MustInitialize() { // SignedBytes returns the serialization of the InnerProposal. func (p *Proposal) SignedBytes() []byte { - data, err := codec.Encode(&BallotMetadata{ + return codec.MustEncode(&BallotMetadata{ Layer: p.Layer, MsgHash: BytesToHash(p.HashInnerProposal()), }) - if err != nil { - log.With().Fatal("failed to serialize BallotMetadata for proposal", log.Err(err)) - } - return data } // HashInnerProposal returns the hash of the InnerProposal. func (p *Proposal) HashInnerProposal() []byte { h := hash.GetHasher() defer hash.PutHasher(h) - _, err := codec.EncodeTo(h, &p.InnerProposal) - if err != nil { - log.With().Fatal("failed to encode InnerProposal for hashing", log.Err(err)) - } + codec.MustEncodeTo(h, &p.InnerProposal) return h.Sum(nil) } @@ -147,7 +140,7 @@ func (p *Proposal) SetBeacon(beacon Beacon) { } // MarshalLogObject implements logging interface. -func (p *Proposal) MarshalLogObject(encoder log.ObjectEncoder) error { +func (p *Proposal) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("proposal_id", p.ID().String()) encoder.AddInt("transactions", len(p.TxIDs)) encoder.AddString("mesh_hash", p.MeshHash.ShortString()) diff --git a/common/types/result/result.go b/common/types/result/result.go index f9d4937fa5..e39e76c259 100644 --- a/common/types/result/result.go +++ b/common/types/result/result.go @@ -3,8 +3,9 @@ package result import ( "fmt" + "go.uber.org/zap/zapcore" + "github.com/spacemeshos/go-spacemesh/common/types" - "github.com/spacemeshos/go-spacemesh/log" ) type Layer struct { @@ -34,13 +35,13 @@ func (l Layer) String() string { return fmt.Sprintf("%d %+v", l.Layer, l.Blocks) } -func (l *Layer) MarshalLogObject(encoder log.ObjectEncoder) error { +func (l *Layer) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddUint32("layer", l.Layer.Uint32()) encoder.AddString("opinion", l.Opinion.ShortString()) encoder.AddBool("verified", l.Verified) - encoder.AddArray("blocks", log.ArrayMarshalerFunc(func(aencoder log.ArrayEncoder) error { + encoder.AddArray("blocks", zapcore.ArrayMarshalerFunc(func(arrayEncoder zapcore.ArrayEncoder) error { for i := range l.Blocks { - aencoder.AppendObject(&l.Blocks[i]) + arrayEncoder.AppendObject(&l.Blocks[i]) } return nil })) @@ -56,7 +57,7 @@ type Block struct { Data bool `json:"d"` } -func (b *Block) MarshalLogObject(encoder log.ObjectEncoder) error { +func (b *Block) MarshalLogObject(encoder zapcore.ObjectEncoder) error { b.Header.MarshalLogObject(encoder) encoder.AddBool("valid", b.Valid) encoder.AddBool("invalid", b.Invalid) diff --git a/common/types/tortoise_data.go b/common/types/tortoise_data.go index d2059b4d83..2097a9a2c3 100644 --- a/common/types/tortoise_data.go +++ b/common/types/tortoise_data.go @@ -1,6 +1,6 @@ package types -import "github.com/spacemeshos/go-spacemesh/log" +import "go.uber.org/zap/zapcore" type BallotTortoiseData struct { ID BallotID `json:"id"` @@ -18,7 +18,7 @@ func (b *BallotTortoiseData) SetMalicious() { b.Malicious = true } -func (b *BallotTortoiseData) MarshalLogObject(encoder log.ObjectEncoder) error { +func (b *BallotTortoiseData) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("id", b.ID.String()) encoder.AddString("smesher", b.Smesher.ShortString()) encoder.AddUint32("layer", b.Layer.Uint32()) @@ -39,7 +39,7 @@ type ReferenceData struct { Eligibilities uint32 `json:"elig"` } -func (r *ReferenceData) MarshalLogObject(encoder log.ObjectEncoder) error { +func (r *ReferenceData) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("beacon", r.Beacon.String()) encoder.AddUint32("elig", r.Eligibilities) return nil diff --git a/common/types/transaction_header.go b/common/types/transaction_header.go index d0dc262339..b798754c34 100644 --- a/common/types/transaction_header.go +++ b/common/types/transaction_header.go @@ -1,6 +1,6 @@ package types -import "github.com/spacemeshos/go-spacemesh/log" +import "go.uber.org/zap/zapcore" //go:generate scalegen @@ -28,7 +28,7 @@ func (h *TxHeader) Spending() uint64 { } // MarshalLogObject implements encoding for the tx header. -func (h *TxHeader) MarshalLogObject(encoder log.ObjectEncoder) error { +func (h *TxHeader) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("principal", h.Principal.String()) encoder.AddUint64("nonce_counter", h.Nonce) encoder.AddUint32("layer_min", h.LayerLimits.Min) diff --git a/common/types/transaction_result.go b/common/types/transaction_result.go index a863d75e20..8cf9724610 100644 --- a/common/types/transaction_result.go +++ b/common/types/transaction_result.go @@ -1,8 +1,6 @@ package types -import ( - "github.com/spacemeshos/go-spacemesh/log" -) +import "go.uber.org/zap/zapcore" //go:generate scalegen @@ -42,7 +40,7 @@ type TransactionResult struct { } // MarshalLogObject implements encoding for the tx result. -func (h *TransactionResult) MarshalLogObject(encoder log.ObjectEncoder) error { +func (h *TransactionResult) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("status", h.Status.String()) if h.Status > 0 { encoder.AddString("message", h.Message) @@ -51,9 +49,9 @@ func (h *TransactionResult) MarshalLogObject(encoder log.ObjectEncoder) error { encoder.AddUint64("fee", h.Fee) encoder.AddString("block", h.Block.String()) encoder.AddUint32("layer", h.Layer.Uint32()) - encoder.AddArray("addresses", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + encoder.AddArray("addresses", zapcore.ArrayMarshalerFunc(func(arrayEncoder zapcore.ArrayEncoder) error { for i := range h.Addresses { - encoder.AppendString((&h.Addresses[i]).String()) + arrayEncoder.AppendString((&h.Addresses[i]).String()) } return nil })) diff --git a/events/reporter.go b/events/reporter.go index f4f1d4b8c8..1d3770a054 100644 --- a/events/reporter.go +++ b/events/reporter.go @@ -83,7 +83,11 @@ func ReportNewActivation(activation *types.ActivationTx) { if reporter != nil { if err := reporter.activationEmitter.Emit(activationTxEvent); err != nil { // TODO(nkryuchkov): consider returning an error and log outside the function - log.With().Error("Failed to emit activation", activation.ID(), activation.PublishEpoch, log.Err(err)) + log.With().Error("Failed to emit activation", + log.ShortStringer("atx_id", activation.ID()), + activation.PublishEpoch, + log.Err(err), + ) } } } diff --git a/fetch/wire_types.go b/fetch/wire_types.go index 5ac39fb23b..bd5ce8cc28 100644 --- a/fetch/wire_types.go +++ b/fetch/wire_types.go @@ -4,10 +4,10 @@ import ( "fmt" "github.com/spacemeshos/go-scale" + "go.uber.org/zap/zapcore" "github.com/spacemeshos/go-spacemesh/common/types" "github.com/spacemeshos/go-spacemesh/datastore" - "github.com/spacemeshos/go-spacemesh/log" "github.com/spacemeshos/go-spacemesh/p2p" ) @@ -103,7 +103,7 @@ func (r *MeshHashRequest) Validate() error { return nil } -func (r *MeshHashRequest) MarshalLogObject(encoder log.ObjectEncoder) error { +func (r *MeshHashRequest) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddUint32("from", r.From.Uint32()) encoder.AddUint32("to", r.To.Uint32()) encoder.AddUint32("by", r.Step) @@ -173,7 +173,7 @@ func (lo *LayerOpinion) Peer() p2p.Peer { } // MarshalLogObject implements logging encoder for LayerOpinion. -func (lo *LayerOpinion) MarshalLogObject(encoder log.ObjectEncoder) error { +func (lo *LayerOpinion) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("peer", lo.peer.String()) encoder.AddString("prev hash", lo.PrevAggHash.String()) encoder.AddBool("has cert", lo.Certified != nil) diff --git a/hare3/protocol.go b/hare3/protocol.go index be89eeb7bc..7bd3157edd 100644 --- a/hare3/protocol.go +++ b/hare3/protocol.go @@ -10,7 +10,6 @@ import ( "golang.org/x/exp/maps" "github.com/spacemeshos/go-spacemesh/common/types" - "github.com/spacemeshos/go-spacemesh/log" "github.com/spacemeshos/go-spacemesh/malfeasance/wire" ) @@ -77,7 +76,7 @@ func (o *output) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddBool("coin", *o.coin) } if o.result != nil { - encoder.AddArray("result", zapcore.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + encoder.AddArray("result", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { for _, id := range o.result { encoder.AppendString(types.Hash20(id).ShortString()) } diff --git a/hare3/types.go b/hare3/types.go index b94800c207..e974d1ab77 100644 --- a/hare3/types.go +++ b/hare3/types.go @@ -9,7 +9,6 @@ import ( "github.com/spacemeshos/go-spacemesh/codec" "github.com/spacemeshos/go-spacemesh/common/types" "github.com/spacemeshos/go-spacemesh/hash" - "github.com/spacemeshos/go-spacemesh/log" "github.com/spacemeshos/go-spacemesh/malfeasance/wire" ) @@ -158,7 +157,7 @@ func (m *Message) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("round", m.Round.String()) encoder.AddString("sender", m.Sender.ShortString()) if m.Value.Proposals != nil { - encoder.AddArray("full", zapcore.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + encoder.AddArray("full", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { for _, id := range m.Value.Proposals { encoder.AppendString(types.Hash20(id).ShortString()) } diff --git a/hare4/protocol.go b/hare4/protocol.go index 0046a49534..34b58f1d86 100644 --- a/hare4/protocol.go +++ b/hare4/protocol.go @@ -10,7 +10,6 @@ import ( "golang.org/x/exp/maps" "github.com/spacemeshos/go-spacemesh/common/types" - "github.com/spacemeshos/go-spacemesh/log" "github.com/spacemeshos/go-spacemesh/malfeasance/wire" ) @@ -77,7 +76,7 @@ func (o *output) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddBool("coin", *o.coin) } if o.result != nil { - encoder.AddArray("result", zapcore.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + encoder.AddArray("result", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { for _, id := range o.result { encoder.AppendString(types.Hash20(id).ShortString()) } diff --git a/hare4/types.go b/hare4/types.go index 3837fcb973..e1cbebbb95 100644 --- a/hare4/types.go +++ b/hare4/types.go @@ -9,7 +9,6 @@ import ( "github.com/spacemeshos/go-spacemesh/codec" "github.com/spacemeshos/go-spacemesh/common/types" "github.com/spacemeshos/go-spacemesh/hash" - "github.com/spacemeshos/go-spacemesh/log" "github.com/spacemeshos/go-spacemesh/malfeasance/wire" ) @@ -161,7 +160,7 @@ func (m *Message) MarshalLogObject(encoder zapcore.ObjectEncoder) error { encoder.AddString("round", m.Round.String()) encoder.AddString("sender", m.Sender.ShortString()) if m.Value.Proposals != nil { - encoder.AddArray("full", zapcore.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + encoder.AddArray("full", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { for _, id := range m.Value.Proposals { encoder.AppendString(types.Hash20(id).ShortString()) } diff --git a/log/context_test.go b/log/context_test.go index 82f567b336..f5484e3e54 100644 --- a/log/context_test.go +++ b/log/context_test.go @@ -1,4 +1,4 @@ -package log_test +package log import ( "bytes" @@ -9,8 +9,6 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/zap" "go.uber.org/zap/zapcore" - - "github.com/spacemeshos/go-spacemesh/log" ) type nopSync struct { @@ -28,8 +26,8 @@ func TestShortUUID(t *testing.T) { &nopSync{Buffer: &buf}, zap.NewAtomicLevelAt(zapcore.InfoLevel), ) - logger := log.NewFromLog(zap.New(core)) - session := log.WithNewSessionID(context.Background()) + logger := NewFromLog(zap.New(core)) + session := WithNewSessionID(context.Background()) logger.WithContext(session).Info("test") type msg struct { Session string `json:"sessionId"` diff --git a/log/log.go b/log/log.go index 1a5dc3750e..7a1b4d472f 100644 --- a/log/log.go +++ b/log/log.go @@ -15,16 +15,8 @@ import ( // mainLoggerName is a name of the global logger. const mainLoggerName = "00000.defaultLogger" -// should we format out logs in json. -var jsonLog = false - // where logs go by default. -var logwriter io.Writer - -// default encoders. -var defaultEncoder = zap.NewDevelopmentEncoderConfig() - -//go:generate mockgen -typed -package=log -destination=./log_mock.go -source=./log.go +var logWriter io.Writer = os.Stdout // Logger is an interface for our logging API. type Logger interface { @@ -38,13 +30,6 @@ type Logger interface { WithName(string) Log } -func encoder() zapcore.Encoder { - if jsonLog { - return zapcore.NewJSONEncoder(defaultEncoder) - } - return zapcore.NewConsoleEncoder(defaultEncoder) -} - // AppLog is the local app singleton logger. var ( mu sync.RWMutex @@ -59,36 +44,18 @@ func GetLogger() Log { return AppLog } -// SetLogger sets logger. -func SetLogger(logger Log) { - mu.Lock() - defer mu.Unlock() - - AppLog = logger -} - // SetupGlobal overwrites global logger. func SetupGlobal(logger Log) { - SetLogger(NewFromLog(logger.logger.Named(mainLoggerName))) + mu.Lock() + defer mu.Unlock() + AppLog = NewFromLog(logger.logger.Named(mainLoggerName)) } func init() { - logwriter = os.Stdout - - // create a basic temp os.Stdout logger - initLogging() -} - -func initLogging() { - SetLogger(NewDefault(mainLoggerName)) -} - -// JSONLog turns JSON format on or off. -func JSONLog(b bool) { - jsonLog = b - - // Need to reinitialize - initLogging() + SetupGlobal(NewWithLevel(mainLoggerName, + zap.NewAtomicLevelAt(zapcore.InfoLevel), + zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()), + )) } // NewNop creates silent logger. @@ -97,19 +64,17 @@ func NewNop() Log { } // NewWithLevel creates a logger with a fixed level and with a set of (optional) hooks. -func NewWithLevel(module string, level zap.AtomicLevel, hooks ...func(zapcore.Entry) error) Log { - consoleSyncer := zapcore.AddSync(logwriter) - enc := encoder() - core := zapcore.NewCore(enc, consoleSyncer, level) +func NewWithLevel(module string, + level zap.AtomicLevel, + encoder zapcore.Encoder, + hooks ...func(zapcore.Entry) error, +) Log { + consoleSyncer := zapcore.AddSync(logWriter) + core := zapcore.NewCore(encoder, consoleSyncer, level) log := zap.New(zapcore.RegisterHooks(core, hooks...)).Named(module) return NewFromLog(log) } -// NewDefault creates a Log with the default log level. -func NewDefault(module string) Log { - return NewWithLevel(module, zap.NewAtomicLevelAt(zapcore.InfoLevel)) -} - // NewFromLog creates a Log from an existing zap-compatible log. func NewFromLog(l *zap.Logger) Log { return Log{logger: l} @@ -132,11 +97,6 @@ func Warning(msg string, args ...any) { GetLogger().Warning(msg, args...) } -// Fatal prints formatted error level log message. -func Fatal(msg string, args ...any) { - GetLogger().Fatal(msg, args...) -} - // With returns a FieldLogger which you can append fields to. func With() FieldLogger { return FieldLogger{GetLogger().logger, GetLogger().name} @@ -146,18 +106,3 @@ func With() FieldLogger { func Panic(msg string, args ...any) { GetLogger().Panic(msg, args...) } - -type ( - // ObjectMarshaller is an alias to zapcore.ObjectMarshaller. - ObjectMarshaller = zapcore.ObjectMarshaler - // ObjectMarshallerFunc is an alias to zapcore.ObjectMarshallerFunc. - ObjectMarshallerFunc = zapcore.ObjectMarshalerFunc - // ObjectEncoder is an alias to zapcore.ObjectEncoder. - ObjectEncoder = zapcore.ObjectEncoder - // ArrayMarshaler is an alias to zapcore.ArrayMarshaller. - ArrayMarshaler = zapcore.ArrayMarshaler - // ArrayMarshalerFunc is an alias to zapcore.ArrayMarshallerFunc. - ArrayMarshalerFunc = zapcore.ArrayMarshalerFunc - // ArrayEncoder is an alias to zapcore.ArrayEncoder. - ArrayEncoder = zapcore.ArrayEncoder -) diff --git a/log/log_mock.go b/log/log_mock.go deleted file mode 100644 index a09bc81a2f..0000000000 --- a/log/log_mock.go +++ /dev/null @@ -1,359 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: ./log.go -// -// Generated by this command: -// -// mockgen -typed -package=log -destination=./log_mock.go -source=./log.go -// - -// Package log is a generated GoMock package. -package log - -import ( - context "context" - reflect "reflect" - - gomock "go.uber.org/mock/gomock" -) - -// MockLogger is a mock of Logger interface. -type MockLogger struct { - ctrl *gomock.Controller - recorder *MockLoggerMockRecorder -} - -// MockLoggerMockRecorder is the mock recorder for MockLogger. -type MockLoggerMockRecorder struct { - mock *MockLogger -} - -// NewMockLogger creates a new mock instance. -func NewMockLogger(ctrl *gomock.Controller) *MockLogger { - mock := &MockLogger{ctrl: ctrl} - mock.recorder = &MockLoggerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockLogger) EXPECT() *MockLoggerMockRecorder { - return m.recorder -} - -// Debug mocks base method. -func (m *MockLogger) Debug(format string, args ...any) { - m.ctrl.T.Helper() - varargs := []any{format} - for _, a := range args { - varargs = append(varargs, a) - } - m.ctrl.Call(m, "Debug", varargs...) -} - -// Debug indicates an expected call of Debug. -func (mr *MockLoggerMockRecorder) Debug(format any, args ...any) *MockLoggerDebugCall { - mr.mock.ctrl.T.Helper() - varargs := append([]any{format}, args...) - call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Debug", reflect.TypeOf((*MockLogger)(nil).Debug), varargs...) - return &MockLoggerDebugCall{Call: call} -} - -// MockLoggerDebugCall wrap *gomock.Call -type MockLoggerDebugCall struct { - *gomock.Call -} - -// Return rewrite *gomock.Call.Return -func (c *MockLoggerDebugCall) Return() *MockLoggerDebugCall { - c.Call = c.Call.Return() - return c -} - -// Do rewrite *gomock.Call.Do -func (c *MockLoggerDebugCall) Do(f func(string, ...any)) *MockLoggerDebugCall { - c.Call = c.Call.Do(f) - return c -} - -// DoAndReturn rewrite *gomock.Call.DoAndReturn -func (c *MockLoggerDebugCall) DoAndReturn(f func(string, ...any)) *MockLoggerDebugCall { - c.Call = c.Call.DoAndReturn(f) - return c -} - -// Error mocks base method. -func (m *MockLogger) Error(format string, args ...any) { - m.ctrl.T.Helper() - varargs := []any{format} - for _, a := range args { - varargs = append(varargs, a) - } - m.ctrl.Call(m, "Error", varargs...) -} - -// Error indicates an expected call of Error. -func (mr *MockLoggerMockRecorder) Error(format any, args ...any) *MockLoggerErrorCall { - mr.mock.ctrl.T.Helper() - varargs := append([]any{format}, args...) - call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Error", reflect.TypeOf((*MockLogger)(nil).Error), varargs...) - return &MockLoggerErrorCall{Call: call} -} - -// MockLoggerErrorCall wrap *gomock.Call -type MockLoggerErrorCall struct { - *gomock.Call -} - -// Return rewrite *gomock.Call.Return -func (c *MockLoggerErrorCall) Return() *MockLoggerErrorCall { - c.Call = c.Call.Return() - return c -} - -// Do rewrite *gomock.Call.Do -func (c *MockLoggerErrorCall) Do(f func(string, ...any)) *MockLoggerErrorCall { - c.Call = c.Call.Do(f) - return c -} - -// DoAndReturn rewrite *gomock.Call.DoAndReturn -func (c *MockLoggerErrorCall) DoAndReturn(f func(string, ...any)) *MockLoggerErrorCall { - c.Call = c.Call.DoAndReturn(f) - return c -} - -// Info mocks base method. -func (m *MockLogger) Info(format string, args ...any) { - m.ctrl.T.Helper() - varargs := []any{format} - for _, a := range args { - varargs = append(varargs, a) - } - m.ctrl.Call(m, "Info", varargs...) -} - -// Info indicates an expected call of Info. -func (mr *MockLoggerMockRecorder) Info(format any, args ...any) *MockLoggerInfoCall { - mr.mock.ctrl.T.Helper() - varargs := append([]any{format}, args...) - call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Info", reflect.TypeOf((*MockLogger)(nil).Info), varargs...) - return &MockLoggerInfoCall{Call: call} -} - -// MockLoggerInfoCall wrap *gomock.Call -type MockLoggerInfoCall struct { - *gomock.Call -} - -// Return rewrite *gomock.Call.Return -func (c *MockLoggerInfoCall) Return() *MockLoggerInfoCall { - c.Call = c.Call.Return() - return c -} - -// Do rewrite *gomock.Call.Do -func (c *MockLoggerInfoCall) Do(f func(string, ...any)) *MockLoggerInfoCall { - c.Call = c.Call.Do(f) - return c -} - -// DoAndReturn rewrite *gomock.Call.DoAndReturn -func (c *MockLoggerInfoCall) DoAndReturn(f func(string, ...any)) *MockLoggerInfoCall { - c.Call = c.Call.DoAndReturn(f) - return c -} - -// Panic mocks base method. -func (m *MockLogger) Panic(format string, args ...any) { - m.ctrl.T.Helper() - varargs := []any{format} - for _, a := range args { - varargs = append(varargs, a) - } - m.ctrl.Call(m, "Panic", varargs...) -} - -// Panic indicates an expected call of Panic. -func (mr *MockLoggerMockRecorder) Panic(format any, args ...any) *MockLoggerPanicCall { - mr.mock.ctrl.T.Helper() - varargs := append([]any{format}, args...) - call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Panic", reflect.TypeOf((*MockLogger)(nil).Panic), varargs...) - return &MockLoggerPanicCall{Call: call} -} - -// MockLoggerPanicCall wrap *gomock.Call -type MockLoggerPanicCall struct { - *gomock.Call -} - -// Return rewrite *gomock.Call.Return -func (c *MockLoggerPanicCall) Return() *MockLoggerPanicCall { - c.Call = c.Call.Return() - return c -} - -// Do rewrite *gomock.Call.Do -func (c *MockLoggerPanicCall) Do(f func(string, ...any)) *MockLoggerPanicCall { - c.Call = c.Call.Do(f) - return c -} - -// DoAndReturn rewrite *gomock.Call.DoAndReturn -func (c *MockLoggerPanicCall) DoAndReturn(f func(string, ...any)) *MockLoggerPanicCall { - c.Call = c.Call.DoAndReturn(f) - return c -} - -// Warning mocks base method. -func (m *MockLogger) Warning(format string, args ...any) { - m.ctrl.T.Helper() - varargs := []any{format} - for _, a := range args { - varargs = append(varargs, a) - } - m.ctrl.Call(m, "Warning", varargs...) -} - -// Warning indicates an expected call of Warning. -func (mr *MockLoggerMockRecorder) Warning(format any, args ...any) *MockLoggerWarningCall { - mr.mock.ctrl.T.Helper() - varargs := append([]any{format}, args...) - call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Warning", reflect.TypeOf((*MockLogger)(nil).Warning), varargs...) - return &MockLoggerWarningCall{Call: call} -} - -// MockLoggerWarningCall wrap *gomock.Call -type MockLoggerWarningCall struct { - *gomock.Call -} - -// Return rewrite *gomock.Call.Return -func (c *MockLoggerWarningCall) Return() *MockLoggerWarningCall { - c.Call = c.Call.Return() - return c -} - -// Do rewrite *gomock.Call.Do -func (c *MockLoggerWarningCall) Do(f func(string, ...any)) *MockLoggerWarningCall { - c.Call = c.Call.Do(f) - return c -} - -// DoAndReturn rewrite *gomock.Call.DoAndReturn -func (c *MockLoggerWarningCall) DoAndReturn(f func(string, ...any)) *MockLoggerWarningCall { - c.Call = c.Call.DoAndReturn(f) - return c -} - -// With mocks base method. -func (m *MockLogger) With() FieldLogger { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "With") - ret0, _ := ret[0].(FieldLogger) - return ret0 -} - -// With indicates an expected call of With. -func (mr *MockLoggerMockRecorder) With() *MockLoggerWithCall { - mr.mock.ctrl.T.Helper() - call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "With", reflect.TypeOf((*MockLogger)(nil).With)) - return &MockLoggerWithCall{Call: call} -} - -// MockLoggerWithCall wrap *gomock.Call -type MockLoggerWithCall struct { - *gomock.Call -} - -// Return rewrite *gomock.Call.Return -func (c *MockLoggerWithCall) Return(arg0 FieldLogger) *MockLoggerWithCall { - c.Call = c.Call.Return(arg0) - return c -} - -// Do rewrite *gomock.Call.Do -func (c *MockLoggerWithCall) Do(f func() FieldLogger) *MockLoggerWithCall { - c.Call = c.Call.Do(f) - return c -} - -// DoAndReturn rewrite *gomock.Call.DoAndReturn -func (c *MockLoggerWithCall) DoAndReturn(f func() FieldLogger) *MockLoggerWithCall { - c.Call = c.Call.DoAndReturn(f) - return c -} - -// WithContext mocks base method. -func (m *MockLogger) WithContext(arg0 context.Context) Log { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WithContext", arg0) - ret0, _ := ret[0].(Log) - return ret0 -} - -// WithContext indicates an expected call of WithContext. -func (mr *MockLoggerMockRecorder) WithContext(arg0 any) *MockLoggerWithContextCall { - mr.mock.ctrl.T.Helper() - call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WithContext", reflect.TypeOf((*MockLogger)(nil).WithContext), arg0) - return &MockLoggerWithContextCall{Call: call} -} - -// MockLoggerWithContextCall wrap *gomock.Call -type MockLoggerWithContextCall struct { - *gomock.Call -} - -// Return rewrite *gomock.Call.Return -func (c *MockLoggerWithContextCall) Return(arg0 Log) *MockLoggerWithContextCall { - c.Call = c.Call.Return(arg0) - return c -} - -// Do rewrite *gomock.Call.Do -func (c *MockLoggerWithContextCall) Do(f func(context.Context) Log) *MockLoggerWithContextCall { - c.Call = c.Call.Do(f) - return c -} - -// DoAndReturn rewrite *gomock.Call.DoAndReturn -func (c *MockLoggerWithContextCall) DoAndReturn(f func(context.Context) Log) *MockLoggerWithContextCall { - c.Call = c.Call.DoAndReturn(f) - return c -} - -// WithName mocks base method. -func (m *MockLogger) WithName(arg0 string) Log { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WithName", arg0) - ret0, _ := ret[0].(Log) - return ret0 -} - -// WithName indicates an expected call of WithName. -func (mr *MockLoggerMockRecorder) WithName(arg0 any) *MockLoggerWithNameCall { - mr.mock.ctrl.T.Helper() - call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WithName", reflect.TypeOf((*MockLogger)(nil).WithName), arg0) - return &MockLoggerWithNameCall{Call: call} -} - -// MockLoggerWithNameCall wrap *gomock.Call -type MockLoggerWithNameCall struct { - *gomock.Call -} - -// Return rewrite *gomock.Call.Return -func (c *MockLoggerWithNameCall) Return(arg0 Log) *MockLoggerWithNameCall { - c.Call = c.Call.Return(arg0) - return c -} - -// Do rewrite *gomock.Call.Do -func (c *MockLoggerWithNameCall) Do(f func(string) Log) *MockLoggerWithNameCall { - c.Call = c.Call.Do(f) - return c -} - -// DoAndReturn rewrite *gomock.Call.DoAndReturn -func (c *MockLoggerWithNameCall) DoAndReturn(f func(string) Log) *MockLoggerWithNameCall { - c.Call = c.Call.DoAndReturn(f) - return c -} diff --git a/log/log_test.go b/log/log_test.go index 55260e0d38..cc14be0a79 100644 --- a/log/log_test.go +++ b/log/log_test.go @@ -34,18 +34,30 @@ func TestLogLevel(t *testing.T) { } // Make it easier to read the logs - defaultEncoder.TimeKey = "" + encoder := zap.NewDevelopmentEncoderConfig() + encoder.TimeKey = "" // Capture the log output var buf bytes.Buffer - logwriter = &buf - AppLog = NewWithLevel(mainLoggerName, zap.NewAtomicLevelAt(zapcore.DebugLevel)) + logWriter = &buf + core := zapcore.NewCore( + zapcore.NewConsoleEncoder(encoder), + &nopSync{Buffer: &buf}, + zap.NewAtomicLevelAt(zapcore.InfoLevel), + ) + logger := NewFromLog(zap.New(core)) + SetupGlobal(logger) // Instantiate a logger and a sublogger nid := FakeNodeID{key: "abc123"} nidEncoded := fmt.Sprintf("{\"node_id\": \"%s\"}", nid.key) loggerName := "logtest" - logger := NewWithLevel(loggerName, zap.NewAtomicLevelAt(zapcore.InfoLevel), hookFn).WithFields(nid) + logger = NewWithLevel( + loggerName, + zap.NewAtomicLevelAt(zapcore.InfoLevel), + zapcore.NewConsoleEncoder(encoder), + hookFn, + ).WithFields(nid) lvl := zap.NewAtomicLevel() r.NoError(lvl.UnmarshalText([]byte("INFO"))) @@ -100,49 +112,12 @@ func TestLogLevel(t *testing.T) { r.Equal(hookedExpected, hooked, "hook function was not called the expected number of times") } -func TestJsonLog(t *testing.T) { - r := require.New(t) - - // Make it easier to read the logs - defaultEncoder.TimeKey = "" - - // Capture the log output - var buf bytes.Buffer - logwriter = &buf - AppLog = NewDefault(mainLoggerName) - - // Expect output not to be in JSON format - teststr := "test001" - Info(teststr) - r.Equal(fmt.Sprintf("INFO\t%s\t%s\n", mainLoggerName, teststr), buf.String()) - buf.Reset() - - // Enable JSON mode - JSONLog(true) - - // Expect output to be in JSON format - teststr = "test002" - type entry struct { - L, M, N string - } - expect := entry{ - L: "INFO", - M: teststr, - N: mainLoggerName, - } - Info(teststr) - got := entry{} - r.NoError(json.Unmarshal(buf.Bytes(), &got)) - r.Equal(expect, got) -} - func TestContextualLogging(t *testing.T) { // basic housekeeping r := require.New(t) reqID := "myRequestId" sesID := "mySessionId" teststr := "test003" - JSONLog(true) // test basic context first: try to set and read context, roundtrip ctx := context.Background() @@ -198,12 +173,16 @@ func TestContextualLogging(t *testing.T) { // Capture the log output var buf bytes.Buffer - logwriter = &buf - AppLog = NewDefault(mainLoggerName) + core := zapcore.NewCore( + zapcore.NewJSONEncoder(zap.NewDevelopmentEncoderConfig()), + &nopSync{Buffer: &buf}, + zap.NewAtomicLevelAt(zapcore.InfoLevel), + ) + logger := NewFromLog(zap.New(core).Named(mainLoggerName)) // make sure we can set and read context ctx = withRequestID(context.Background(), reqID) - contextualLogger := AppLog.WithContext(ctx) + contextualLogger := logger.WithContext(ctx) contextualLogger.Info(teststr) type entry struct { L, M, N, RequestID, SessionID, Foo string @@ -221,7 +200,7 @@ func TestContextualLogging(t *testing.T) { // test extra fields buf.Reset() ctx = WithSessionID(context.Background(), sesID, String("foo", "bar")) - contextualLogger = AppLog.WithContext(ctx) + contextualLogger = logger.WithContext(ctx) contextualLogger.Info(teststr) expect = entry{ L: "INFO", diff --git a/log/logtest/log.go b/log/logtest/log.go index eb84b39ff8..50b54d9cc4 100644 --- a/log/logtest/log.go +++ b/log/logtest/log.go @@ -4,7 +4,6 @@ import ( "os" "testing" - "go.uber.org/zap" "go.uber.org/zap/zapcore" "go.uber.org/zap/zaptest" @@ -13,10 +12,6 @@ import ( const testLogLevel = "TEST_LOG_LEVEL" -func Zap(tb testing.TB, override ...zapcore.Level) *zap.Logger { - return New(tb, override...).Zap() -} - // New creates log.Log instance that will use testing.TB.Log internally. func New(tb testing.TB, override ...zapcore.Level) log.Log { var level zapcore.Level @@ -33,14 +28,3 @@ func New(tb testing.TB, override ...zapcore.Level) log.Log { } return log.NewFromLog(zaptest.NewLogger(tb, zaptest.Level(level))).Named(tb.Name()) } - -// SetupGlobal updates AppLog to the instance of test-specific logger. -// Some tests do not terminate all goroutines when they exit, so we can't recover original for now. -func SetupGlobal(tb testing.TB, overwrite ...zapcore.Level) { - tlog := New(tb, overwrite...) - tmp := log.GetLogger() - log.SetupGlobal(tlog) - tb.Cleanup(func() { - log.SetLogger(tmp) - }) -} diff --git a/log/zap.go b/log/zap.go index 463877f010..6b46170acf 100644 --- a/log/zap.go +++ b/log/zap.go @@ -72,7 +72,7 @@ func FieldNamed(name string, field LoggableField) Field { return f } -func (f Field) AddTo(enc ObjectEncoder) { +func (f Field) AddTo(enc zapcore.ObjectEncoder) { (zapcore.Field)(f).AddTo(enc) } @@ -153,7 +153,7 @@ func Duration(name string, val time.Duration) Field { // Err returns an error field. func Err(err error) Field { - var loggable ObjectMarshaller + var loggable zapcore.ObjectMarshaler if errors.As(err, &loggable) { return Field(zap.Inline(loggable)) } @@ -161,17 +161,17 @@ func Err(err error) Field { } // Object for logging struct fields in namespace. -func Object(namespace string, object ObjectMarshaller) Field { +func Object(namespace string, object zapcore.ObjectMarshaler) Field { return Field(zap.Object(namespace, object)) } // Inline for inline logging. -func Inline(object ObjectMarshaller) Field { +func Inline(object zapcore.ObjectMarshaler) Field { return Field(zap.Inline(object)) } // Array for logging array efficiently. -func Array(name string, array ArrayMarshaler) Field { +func Array(name string, array zapcore.ArrayMarshaler) Field { return Field(zap.Array(name, array)) } @@ -185,7 +185,7 @@ func ZContext(ctx context.Context) zap.Field { } func NiceZapError(err error) zap.Field { - var loggable ObjectMarshaller + var loggable zapcore.ObjectMarshaler if errors.As(err, &loggable) { return zap.Inline(loggable) } @@ -200,7 +200,7 @@ type marshalledContext struct { context.Context } -func (c *marshalledContext) MarshalLogObject(encoder ObjectEncoder) error { +func (c *marshalledContext) MarshalLogObject(encoder zapcore.ObjectEncoder) error { if c.Context != nil { if ctxRequestID, ok := ExtractRequestID(c.Context); ok { encoder.AddString("requestId", ctxRequestID) diff --git a/node/node.go b/node/node.go index a2d6573f66..6c404e41a3 100644 --- a/node/node.go +++ b/node/node.go @@ -146,12 +146,15 @@ func GetCommand() *cobra.Command { return err } - app := New( - WithConfig(&conf), - // NOTE(dshulyak) this needs to be max level so that child logger can can be current level or below. - // otherwise it will fail later when child logger will try to increase level. - WithLog(log.NewWithLevel("node", zap.NewAtomicLevelAt(zap.DebugLevel), events.EventHook())), - ) + // NOTE(dshulyak) this needs to be max level so that child logger can can be current level or below. + // otherwise it will fail later when child logger will try to increase level. + encoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()) + if conf.LOGGING.Encoder == config.JSONLogEncoder { + encoder = zapcore.NewJSONEncoder(zap.NewDevelopmentEncoderConfig()) + } + lg := log.NewWithLevel("node", zap.NewAtomicLevelAt(zap.DebugLevel), encoder, events.EventHook()) + + app := New(WithConfig(&conf), WithLog(lg)) // os.Interrupt for all systems, especially windows, syscall.SIGTERM is mainly for docker. ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) @@ -247,10 +250,6 @@ func configure(c *cobra.Command, configPath string, conf *config.Config) error { return fmt.Errorf("parsing flags: %w", err) } - if conf.LOGGING.Encoder == config.JSONLogEncoder { - log.JSONLog(true) - } - if cmd.NoMainNet && onMainNet(conf) && !conf.NoMainOverride { return errors.New("this is a testnet-only build not intended for mainnet") } @@ -258,15 +257,7 @@ func configure(c *cobra.Command, configPath string, conf *config.Config) error { return nil } -var ( - appLog log.Log - grpclog grpc_logsettable.SettableLoggerV2 -) - -func init() { - appLog = log.NewNop() - grpclog = grpc_logsettable.ReplaceGrpcLoggerV2() -} +var grpcLog = grpc_logsettable.ReplaceGrpcLoggerV2() // loadConfig loads config and preset (if provided) into the provided config. // It first loads the preset and then overrides it with values from the config file. @@ -355,7 +346,7 @@ func New(opts ...Option) *App { defaultConfig := config.DefaultConfig() app := &App{ Config: &defaultConfig, - log: appLog, + log: log.NewNop(), loggers: make(map[string]*zap.AtomicLevel), grpcServices: make(map[grpcserver.Service]grpcserver.ServiceAPI), started: make(chan struct{}), @@ -1591,7 +1582,7 @@ func (app *App) grpcService(svc grpcserver.Service, lg log.Log) (grpcserver.Serv func (app *App) startAPIServices(ctx context.Context) error { logger := app.addLogger(GRPCLogger, app.log) - grpczap.SetGrpcLoggerV2(grpclog, logger.Zap()) + grpczap.SetGrpcLoggerV2(grpcLog, logger.Zap()) var ( publicSvcs = make(map[grpcserver.Service]grpcserver.ServiceAPI, len(app.Config.API.PublicServices)) @@ -1671,7 +1662,7 @@ func (app *App) startAPIServices(ctx context.Context) error { } logger.With().Info("public grpc service started", log.String("address", app.Config.API.PublicListener), - log.Array("services", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + log.Array("services", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { services := maps.Keys(publicSvcs) slices.Sort(services) for _, svc := range services { @@ -1697,7 +1688,7 @@ func (app *App) startAPIServices(ctx context.Context) error { } logger.With().Info("private grpc service started", log.String("address", app.Config.API.PrivateListener), - log.Array("services", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + log.Array("services", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { services := maps.Keys(privateSvcs) slices.Sort(services) for _, svc := range services { @@ -1723,7 +1714,7 @@ func (app *App) startAPIServices(ctx context.Context) error { } logger.With().Info("post grpc service started", log.String("address", app.Config.API.PostListener), - log.Array("services", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + log.Array("services", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { services := maps.Keys(postSvcs) slices.Sort(services) for _, svc := range services { @@ -1783,7 +1774,7 @@ func (app *App) startAPIServices(ctx context.Context) error { } logger.With().Info("authenticated grpc service started", log.String("address", app.Config.API.TLSListener), - log.Array("services", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + log.Array("services", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { services := maps.Keys(authenticatedSvcs) slices.Sort(services) for _, svc := range services { @@ -1810,7 +1801,7 @@ func (app *App) startAPIServices(ctx context.Context) error { } logger.With().Info("json listener started", log.String("address", app.Config.API.JSONListener), - log.Array("services", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + log.Array("services", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { services := maps.Keys(publicSvcs) slices.Sort(services) for _, svc := range services { @@ -1941,7 +1932,7 @@ func (app *App) stopServices(ctx context.Context) { // SetGrpcLogger unfortunately is global // this ensures that a test-logger isn't used after the app shuts down // by e.g. a grpc connection to the node that is still open - like in TestSpacemeshApp_NodeService - grpczap.SetGrpcLoggerV2(grpclog, log.NewNop().Zap()) + grpczap.SetGrpcLoggerV2(grpcLog, log.NewNop().Zap()) } func (app *App) setupDBs(ctx context.Context, lg log.Log) error { diff --git a/systest/tests/partition_test.go b/systest/tests/partition_test.go index ba65b833cc..9d56777f1a 100644 --- a/systest/tests/partition_test.go +++ b/systest/tests/partition_test.go @@ -7,10 +7,10 @@ import ( pb "github.com/spacemeshos/api/release/go/spacemesh/v1" "github.com/stretchr/testify/require" + "go.uber.org/zap/zapcore" "golang.org/x/sync/errgroup" "github.com/spacemeshos/go-spacemesh/common/types" - "github.com/spacemeshos/go-spacemesh/log" "github.com/spacemeshos/go-spacemesh/systest/chaos" "github.com/spacemeshos/go-spacemesh/systest/cluster" "github.com/spacemeshos/go-spacemesh/systest/testcontext" @@ -133,11 +133,11 @@ func testPartition(t *testing.T, tctx *testcontext.Context, cl *cluster.Cluster, tctx.Log.Debugw("client states", "layer", layer, "num_states", len(hashes[layer]), - "states", log.ObjectMarshallerFunc(func(encoder log.ObjectEncoder) error { + "states", zapcore.ObjectMarshalerFunc(func(encoder zapcore.ObjectEncoder) error { for hash, clients := range hashes[layer] { encoder.AddString("hash", hash.ShortString()) encoder.AddInt("num_clients", len(clients)) - encoder.AddArray("clients", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error { + encoder.AddArray("clients", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { for _, c := range clients { encoder.AppendString(c) }