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