github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/network/p2p/connection/internal/loggerNotifiee.go (about)

     1  package internal
     2  
     3  import (
     4  	"github.com/libp2p/go-libp2p/core/network"
     5  	"github.com/multiformats/go-multiaddr"
     6  	"github.com/rs/zerolog"
     7  
     8  	"github.com/onflow/flow-go/module"
     9  	p2plogging "github.com/onflow/flow-go/network/p2p/logging"
    10  )
    11  
    12  type LoggerNotifiee struct {
    13  	logger  zerolog.Logger
    14  	metrics module.LibP2PConnectionMetrics
    15  }
    16  
    17  var _ network.Notifiee = (*LoggerNotifiee)(nil)
    18  
    19  func NewLoggerNotifiee(logger zerolog.Logger, metrics module.LibP2PConnectionMetrics) *LoggerNotifiee {
    20  	return &LoggerNotifiee{
    21  		logger:  logger,
    22  		metrics: metrics,
    23  	}
    24  }
    25  
    26  func (l *LoggerNotifiee) Listen(_ network.Network, multiaddr multiaddr.Multiaddr) {
    27  	// just log the multiaddress on which we listen
    28  	l.logger.Debug().Str("multiaddress", multiaddr.String()).Msg("listen started")
    29  }
    30  
    31  func (l *LoggerNotifiee) ListenClose(_ network.Network, multiaddr multiaddr.Multiaddr) {
    32  	l.logger.Debug().Str("multiaddress", multiaddr.String()).Msg("listen stopped")
    33  }
    34  
    35  func (l *LoggerNotifiee) Connected(n network.Network, conn network.Conn) {
    36  	l.updateConnectionMetric(n)
    37  	lg := l.connectionUpdateLogger(n, conn)
    38  	lg.Debug().Msg("connection established")
    39  }
    40  
    41  func (l *LoggerNotifiee) Disconnected(n network.Network, conn network.Conn) {
    42  	l.updateConnectionMetric(n)
    43  	lg := l.connectionUpdateLogger(n, conn)
    44  	lg.Debug().Msg("connection closed")
    45  }
    46  
    47  func (l *LoggerNotifiee) connectionUpdateLogger(n network.Network, con network.Conn) zerolog.Logger {
    48  	return l.logger.With().
    49  		Str("remote_peer", p2plogging.PeerId(con.RemotePeer())).
    50  		Str("remote_address", con.RemoteMultiaddr().String()).
    51  		Str("local_peer", p2plogging.PeerId(con.LocalPeer())).
    52  		Str("local_address", con.LocalMultiaddr().String()).
    53  		Str("direction", con.Stat().Direction.String()).
    54  		Int("total_connections", len(n.Conns())).Logger()
    55  }
    56  
    57  func (l *LoggerNotifiee) updateConnectionMetric(n network.Network) {
    58  	var totalInbound uint = 0
    59  	var totalOutbound uint = 0
    60  
    61  	for _, conn := range n.Conns() {
    62  		switch conn.Stat().Direction {
    63  		case network.DirInbound:
    64  			totalInbound++
    65  		case network.DirOutbound:
    66  			totalOutbound++
    67  		}
    68  	}
    69  
    70  	l.metrics.InboundConnections(totalInbound)
    71  	l.metrics.OutboundConnections(totalOutbound)
    72  }