Skip to content

Commit dc0a006

Browse files
authored
Merge pull request bnb-chain#3718 from karalabe/terminal-format-hash
common, eth/downloader, log: support terminal log formatting
2 parents fc97c7a + 2f28a12 commit dc0a006

4 files changed

Lines changed: 61 additions & 34 deletions

File tree

‎common/types.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,24 @@ func (h Hash) Bytes() []byte { return h[:] }
5555
func (h Hash) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }
5656
func (h Hash) Hex() string { return hexutil.Encode(h[:]) }
5757

58+
// TerminalString implements log.TerminalStringer, formatting a string for console
59+
// output during logging.
60+
func (h Hash) TerminalString() string {
61+
return fmt.Sprintf("%x…%x", h[:3], h[29:])
62+
}
63+
64+
// String implements the stringer interface and is used also by the logger when
65+
// doing full logging into a file.
66+
func (h Hash) String() string {
67+
return h.Hex()
68+
}
69+
70+
// Format implements fmt.Formatter, forcing the byte slice to be formatted as is,
71+
// without going through the stringer interface used for logging.
72+
func (h Hash) Format(s fmt.State, c rune) {
73+
fmt.Fprintf(s, "%"+string(c), h[:])
74+
}
75+
5876
// UnmarshalJSON parses a hash in its hex from to a hash.
5977
func (h *Hash) UnmarshalJSON(input []byte) error {
6078
return hexutil.UnmarshalJSON("Hash", input, h[:])

‎eth/downloader/downloader.go‎

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ func (d *Downloader) syncWithPeer(p *peer, hash common.Hash, td *big.Int) (err e
383383
return errTooOld
384384
}
385385

386-
log.Debug("Synchronising with the network", "peer", p.id, "eth", p.version, "head", hash.Hex()[2:10], "td", td, "mode", d.mode)
386+
log.Debug("Synchronising with the network", "peer", p.id, "eth", p.version, "head", hash, "td", td, "mode", d.mode)
387387
defer func(start time.Time) {
388388
log.Debug("Synchronisation terminated", "elapsed", time.Since(start))
389389
}(time.Now())
@@ -544,7 +544,7 @@ func (d *Downloader) fetchHeight(p *peer) (*types.Header, error) {
544544
return nil, errBadPeer
545545
}
546546
head := headers[0]
547-
p.logger.Debug("Remote head header identified", "number", head.Number, "hash", head.Hash().Hex()[2:10])
547+
p.logger.Debug("Remote head header identified", "number", head.Number, "hash", head.Hash())
548548
return head, nil
549549

550550
case <-timeout:
@@ -657,10 +657,10 @@ func (d *Downloader) findAncestor(p *peer, height uint64) (uint64, error) {
657657
// If the head fetch already found an ancestor, return
658658
if !common.EmptyHash(hash) {
659659
if int64(number) <= floor {
660-
p.logger.Warn("Ancestor below allowance", "number", number, "hash", hash.Hex()[2:10], "allowance", floor)
660+
p.logger.Warn("Ancestor below allowance", "number", number, "hash", hash, "allowance", floor)
661661
return 0, errInvalidAncestor
662662
}
663-
p.logger.Debug("Found common ancestor", "number", number, "hash", hash.Hex()[2:10])
663+
p.logger.Debug("Found common ancestor", "number", number, "hash", hash)
664664
return number, nil
665665
}
666666
// Ancestor not found, we need to binary search over our chain
@@ -704,7 +704,7 @@ func (d *Downloader) findAncestor(p *peer, height uint64) (uint64, error) {
704704
}
705705
header := d.getHeader(headers[0].Hash()) // Independent of sync mode, header surely exists
706706
if header.Number.Uint64() != check {
707-
p.logger.Debug("Received non requested header", "number", header.Number, "hash", header.Hash().Hex()[2:10], "request", check)
707+
p.logger.Debug("Received non requested header", "number", header.Number, "hash", header.Hash(), "request", check)
708708
return 0, errBadPeer
709709
}
710710
start = check
@@ -722,10 +722,10 @@ func (d *Downloader) findAncestor(p *peer, height uint64) (uint64, error) {
722722
}
723723
// Ensure valid ancestry and return
724724
if int64(start) <= floor {
725-
p.logger.Warn("Ancestor below allowance", "number", start, "hash", hash.Hex()[2:10], "allowance", floor)
725+
p.logger.Warn("Ancestor below allowance", "number", start, "hash", hash, "allowance", floor)
726726
return 0, errInvalidAncestor
727727
}
728-
p.logger.Debug("Found common ancestor", "number", start, "hash", hash.Hex()[2:10])
728+
p.logger.Debug("Found common ancestor", "number", start, "hash", hash)
729729
return start, nil
730730
}
731731

@@ -1208,7 +1208,7 @@ func (d *Downloader) processHeaders(origin uint64, td *big.Int) error {
12081208
if atomic.LoadUint32(&d.fsPivotFails) == 0 {
12091209
for _, header := range rollback {
12101210
if header.Number.Uint64() == pivot {
1211-
log.Warn("Fast-sync critical section failure, locked pivot to header", "number", pivot, "hash", header.Hash().Hex()[2:10])
1211+
log.Warn("Fast-sync critical section failure, locked pivot to header", "number", pivot, "hash", header.Hash())
12121212
d.fsPivotLock = header
12131213
}
12141214
}
@@ -1304,7 +1304,7 @@ func (d *Downloader) processHeaders(origin uint64, td *big.Int) error {
13041304
if n > 0 {
13051305
rollback = append(rollback, chunk[:n]...)
13061306
}
1307-
log.Debug("Invalid header encountered", "number", chunk[n].Number, "hash", chunk[n].Hash().Hex()[2:10], "err", err)
1307+
log.Debug("Invalid header encountered", "number", chunk[n].Number, "hash", chunk[n].Hash(), "err", err)
13081308
return errInvalidChain
13091309
}
13101310
// All verifications passed, store newly found uncertain headers
@@ -1316,7 +1316,7 @@ func (d *Downloader) processHeaders(origin uint64, td *big.Int) error {
13161316
// If we're fast syncing and just pulled in the pivot, make sure it's the one locked in
13171317
if d.mode == FastSync && d.fsPivotLock != nil && chunk[0].Number.Uint64() <= pivot && chunk[len(chunk)-1].Number.Uint64() >= pivot {
13181318
if pivot := chunk[int(pivot-chunk[0].Number.Uint64())]; pivot.Hash() != d.fsPivotLock.Hash() {
1319-
log.Warn("Pivot doesn't match locked in one", "remoteNumber", pivot.Number, "remoteHash", pivot.Hash().Hex()[2:10], "localNumber", d.fsPivotLock.Number, "localHash", d.fsPivotLock.Hash().Hex()[2:10])
1319+
log.Warn("Pivot doesn't match locked in one", "remoteNumber", pivot.Number, "remoteHash", pivot.Hash(), "localNumber", d.fsPivotLock.Number, "localHash", d.fsPivotLock.Hash())
13201320
return errInvalidChain
13211321
}
13221322
}
@@ -1366,13 +1366,9 @@ func (d *Downloader) processContent() error {
13661366
// Actually import the blocks
13671367
first, last := results[0].Header, results[len(results)-1].Header
13681368
log.Debug("Inserting downloaded chain", "items", len(results),
1369-
"from", log.Lazy{Fn: func() string {
1370-
return fmt.Sprintf("#%d [%x…]", first.Number, first.Hash().Bytes()[:4])
1371-
}},
1372-
"till", log.Lazy{Fn: func() string {
1373-
return fmt.Sprintf("#%d [%x…]", last.Number, last.Hash().Bytes()[:4])
1374-
}})
1375-
1369+
"firstnum", first.Number, "firsthash", first.Hash(),
1370+
"lastnum", last.Number, "lasthash", last.Hash(),
1371+
)
13761372
for len(results) != 0 {
13771373
// Check for any termination requests
13781374
select {
@@ -1406,14 +1402,14 @@ func (d *Downloader) processContent() error {
14061402
case len(receipts) > 0:
14071403
index, err = d.insertReceipts(blocks, receipts)
14081404
if err == nil && blocks[len(blocks)-1].NumberU64() == pivot {
1409-
log.Debug("Committing block as new head", "number", blocks[len(blocks)-1].Number(), "hash", blocks[len(blocks)-1].Hash().Hex()[2:10])
1405+
log.Debug("Committing block as new head", "number", blocks[len(blocks)-1].Number(), "hash", blocks[len(blocks)-1].Hash())
14101406
index, err = len(blocks)-1, d.commitHeadBlock(blocks[len(blocks)-1].Hash())
14111407
}
14121408
default:
14131409
index, err = d.insertBlocks(blocks)
14141410
}
14151411
if err != nil {
1416-
log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash().Hex()[2:10], "err", err)
1412+
log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
14171413
return errInvalidChain
14181414
}
14191415
// Shift the results to the next batch

‎eth/downloader/queue.go‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -364,20 +364,20 @@ func (q *queue) Schedule(headers []*types.Header, from uint64) []*types.Header {
364364
// Make sure chain order is honoured and preserved throughout
365365
hash := header.Hash()
366366
if header.Number == nil || header.Number.Uint64() != from {
367-
log.Warn("Header broke chain ordering", "number", header.Number, "hash", hash.Hex()[2:10], "expected", from)
367+
log.Warn("Header broke chain ordering", "number", header.Number, "hash", hash, "expected", from)
368368
break
369369
}
370370
if q.headerHead != (common.Hash{}) && q.headerHead != header.ParentHash {
371-
log.Warn("Header broke chain ancestry", "number", header.Number, "hash", hash.Hex()[2:10])
371+
log.Warn("Header broke chain ancestry", "number", header.Number, "hash", hash)
372372
break
373373
}
374374
// Make sure no duplicate requests are executed
375375
if _, ok := q.blockTaskPool[hash]; ok {
376-
log.Warn("Header already scheduled for block fetch", "number", header.Number, "hash", hash.Hex()[2:10])
376+
log.Warn("Header already scheduled for block fetch", "number", header.Number, "hash", hash)
377377
continue
378378
}
379379
if _, ok := q.receiptTaskPool[hash]; ok {
380-
log.Warn("Header already scheduled for receipt fetch", "number", header.Number, "hash", hash.Hex()[2:10])
380+
log.Warn("Header already scheduled for receipt fetch", "number", header.Number, "hash", hash)
381381
continue
382382
}
383383
// Queue the header for content retrieval
@@ -391,7 +391,7 @@ func (q *queue) Schedule(headers []*types.Header, from uint64) []*types.Header {
391391
}
392392
if q.mode == FastSync && header.Number.Uint64() == q.fastSyncPivot {
393393
// Pivoting point of the fast sync, switch the state retrieval to this
394-
log.Debug("Switching state downloads to new block", "number", header.Number, "hash", hash.Hex()[2:10])
394+
log.Debug("Switching state downloads to new block", "number", header.Number, "hash", hash)
395395

396396
q.stateTaskIndex = 0
397397
q.stateTaskPool = make(map[common.Hash]int)
@@ -872,23 +872,23 @@ func (q *queue) DeliverHeaders(id string, headers []*types.Header, headerProcCh
872872
accepted := len(headers) == MaxHeaderFetch
873873
if accepted {
874874
if headers[0].Number.Uint64() != request.From {
875-
log.Trace("First header broke chain ordering", "peer", id, "number", headers[0].Number, "hash", headers[0].Hash().Hex()[2:10], request.From)
875+
log.Trace("First header broke chain ordering", "peer", id, "number", headers[0].Number, "hash", headers[0].Hash(), request.From)
876876
accepted = false
877877
} else if headers[len(headers)-1].Hash() != target {
878-
log.Trace("Last header broke skeleton structure ", "peer", id, "number", headers[len(headers)-1].Number, "hash", headers[len(headers)-1].Hash().Hex()[2:10], "expected", target.Hex()[2:10])
878+
log.Trace("Last header broke skeleton structure ", "peer", id, "number", headers[len(headers)-1].Number, "hash", headers[len(headers)-1].Hash(), "expected", target)
879879
accepted = false
880880
}
881881
}
882882
if accepted {
883883
for i, header := range headers[1:] {
884884
hash := header.Hash()
885885
if want := request.From + 1 + uint64(i); header.Number.Uint64() != want {
886-
log.Warn("Header broke chain ordering", "peer", id, "number", header.Number, "hash", hash.Hex()[2:10], "expected", want)
886+
log.Warn("Header broke chain ordering", "peer", id, "number", header.Number, "hash", hash, "expected", want)
887887
accepted = false
888888
break
889889
}
890890
if headers[i].Hash() != header.ParentHash {
891-
log.Warn("Header broke chain ancestry", "peer", id, "number", header.Number, "hash", hash.Hex()[2:10])
891+
log.Warn("Header broke chain ancestry", "peer", id, "number", header.Number, "hash", hash)
892892
accepted = false
893893
break
894894
}

‎log/format.go‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,13 @@ func (f formatFunc) Format(r *Record) []byte {
5959
return f(r)
6060
}
6161

62+
// TerminalStringer is an analogous interface to the stdlib stringer, allowing
63+
// own types to have custom shortened serialization formats when printed to the
64+
// screen.
65+
type TerminalStringer interface {
66+
TerminalString() string
67+
}
68+
6269
// TerminalFormat formats log records optimized for human readability on
6370
// a terminal with color-coded level output and terser human friendly timestamp.
6471
// This format should only be used for interactive programs or while developing.
@@ -124,7 +131,7 @@ func TerminalFormat(usecolor bool) Format {
124131
}
125132

126133
// print the keys logfmt style
127-
logfmt(b, r.Ctx, color)
134+
logfmt(b, r.Ctx, color, true)
128135
return b.Bytes()
129136
})
130137
}
@@ -138,21 +145,21 @@ func LogfmtFormat() Format {
138145
return FormatFunc(func(r *Record) []byte {
139146
common := []interface{}{r.KeyNames.Time, r.Time, r.KeyNames.Lvl, r.Lvl, r.KeyNames.Msg, r.Msg}
140147
buf := &bytes.Buffer{}
141-
logfmt(buf, append(common, r.Ctx...), 0)
148+
logfmt(buf, append(common, r.Ctx...), 0, false)
142149
return buf.Bytes()
143150
})
144151
}
145152

146-
func logfmt(buf *bytes.Buffer, ctx []interface{}, color int) {
153+
func logfmt(buf *bytes.Buffer, ctx []interface{}, color int, term bool) {
147154
for i := 0; i < len(ctx); i += 2 {
148155
if i != 0 {
149156
buf.WriteByte(' ')
150157
}
151158

152159
k, ok := ctx[i].(string)
153-
v := formatLogfmtValue(ctx[i+1])
160+
v := formatLogfmtValue(ctx[i+1], term)
154161
if !ok {
155-
k, v = errorKey, formatLogfmtValue(k)
162+
k, v = errorKey, formatLogfmtValue(k, term)
156163
}
157164

158165
// XXX: we should probably check that all of your key bytes aren't invalid
@@ -253,7 +260,7 @@ func formatJsonValue(value interface{}) interface{} {
253260
}
254261

255262
// formatValue formats a value for serialization
256-
func formatLogfmtValue(value interface{}) string {
263+
func formatLogfmtValue(value interface{}, term bool) string {
257264
if value == nil {
258265
return "nil"
259266
}
@@ -264,6 +271,12 @@ func formatLogfmtValue(value interface{}) string {
264271
// expensive.
265272
return t.Format(timeFormat)
266273
}
274+
if term {
275+
if s, ok := value.(TerminalStringer); ok {
276+
// Custom terminal stringer provided, use that
277+
return escapeString(s.TerminalString())
278+
}
279+
}
267280
value = formatShared(value)
268281
switch v := value.(type) {
269282
case bool:

0 commit comments

Comments
 (0)