github.com/BlockABC/godash@v0.0.0-20191112120524-f4aa3a32c566/blocklogger.go (about)

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