github.com/aergoio/aergo@v1.3.1/p2p/subproto/advice.go (about)

     1  /*
     2   * @file
     3   * @copyright defined in aergo/LICENSE.txt
     4   */
     5  
     6  package subproto
     7  
     8  import (
     9  	"github.com/aergoio/aergo-lib/log"
    10  	"github.com/aergoio/aergo/p2p/p2pcommon"
    11  	"github.com/rs/zerolog"
    12  	"time"
    13  )
    14  
    15  func WithTimeLog(handler p2pcommon.MessageHandler, logger *log.Logger, level zerolog.Level) p2pcommon.MessageHandler {
    16  	handler.AddAdvice(&LogHandleTimeAdvice{logger: logger, level:level})
    17  	return handler
    18  }
    19  
    20  type LogHandleTimeAdvice struct {
    21  	logger    *log.Logger
    22  	level     zerolog.Level
    23  	timestamp time.Time
    24  }
    25  
    26  func (a *LogHandleTimeAdvice) PreHandle() {
    27  	a.timestamp = time.Now()
    28  }
    29  
    30  func (a *LogHandleTimeAdvice) PostHandle(msg p2pcommon.Message, msgBody p2pcommon.MessageBody) {
    31  	a.logger.WithLevel(a.level).
    32  		Str("elapsed", time.Since(a.timestamp).String()).
    33  		Str("protocol", msg.Subprotocol().String()).
    34  		Str("msgid", msg.ID().String()).
    35  		Msg("handle takes")
    36  }