blocklogger.go raw
1 package index
2
3 import (
4 "fmt"
5 "github.com/p9c/p9/pkg/block"
6 "sync"
7 "time"
8 )
9
10 // blockProgressLogger provides periodic logging for other services in order to show users progress of certain "actions"
11 // involving some or all current blocks. Ex: syncing to best chain, indexing all blocks, etc.
12 type blockProgressLogger struct {
13 receivedLogBlocks int64
14 receivedLogTx int64
15 lastBlockLogTime time.Time
16 // subsystemLogger *log.Logger
17 progressAction string
18 sync.Mutex
19 }
20
21 // newBlockProgressLogger returns a new block progress logger. The progress message is templated as follows:
22 // {progressAction} {numProcessed} {blocks|block} in the last {timePeriod}
23 // ({numTxs}, height {lastBlockHeight}, {lastBlockTimeStamp})
24 func newBlockProgressLogger(
25 progressMessage string,
26 // logger *log.Logger
27 ) *blockProgressLogger {
28 return &blockProgressLogger{
29 lastBlockLogTime: time.Now(),
30 progressAction: progressMessage,
31 // subsystemLogger: logger,
32 }
33 }
34
35 // LogBlockHeight logs a new block height as an information message to show progress to the user. In order to prevent
36 // spam, it limits logging to one message every 10 seconds with duration and totals included.
37 func (b *blockProgressLogger) LogBlockHeight(block *block.Block) {
38 b.Lock()
39 defer b.Unlock()
40 b.receivedLogBlocks++
41 b.receivedLogTx += int64(len(block.WireBlock().Transactions))
42 now := time.Now()
43 duration := now.Sub(b.lastBlockLogTime)
44 if duration < time.Second*10 {
45 return
46 }
47 // Truncate the duration to 10s of milliseconds.
48 durationMillis := int64(duration / time.Millisecond)
49 tDuration := 10 * time.Millisecond * time.Duration(durationMillis/10)
50 // Log information about new block height.
51 blockStr := "blocks"
52 if b.receivedLogBlocks == 1 {
53 blockStr = "block "
54 }
55 txStr := "transactions"
56 if b.receivedLogTx == 1 {
57 txStr = "transaction "
58 }
59 I.F(
60 "%s %6d %s in the last %s (%6d %s, height %6d, %s)",
61 b.progressAction,
62 b.receivedLogBlocks,
63 blockStr,
64 fmt.Sprintf("%0.1fs", tDuration.Seconds()),
65 b.receivedLogTx,
66 txStr,
67 block.Height(),
68 block.WireBlock().Header.Timestamp,
69 )
70 b.receivedLogBlocks = 0
71 b.receivedLogTx = 0
72 b.lastBlockLogTime = now
73 }
74