mirror of
https://github.com/libp2p/go-libp2p-core.git
synced 2025-04-28 17:10:14 +08:00
Add canonical peer status log
This commit is contained in:
parent
77522c6e95
commit
7fbd9a2f94
canonicallog
@ -1,7 +1,9 @@
|
||||
package canonicallog
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
logging "github.com/ipfs/go-log/v2"
|
||||
"github.com/libp2p/go-libp2p-core/peer"
|
||||
@ -30,3 +32,26 @@ func LogMisbehavingPeerNetAddr(p peer.ID, peerAddr net.Addr, component string, o
|
||||
|
||||
log.Warnf("CANONICAL_MISBEHAVING_PEER: peer=%s addr=%s component=%s err=%v msg=%s", p, ma, component, originalErr, msg)
|
||||
}
|
||||
|
||||
// LogPeerStatus logs any useful information about a peer. It takes in a sample
|
||||
// rate and will only log one in every sampleRate messages (randomly). This is
|
||||
// useful in surfacing events that are normal in isolation, but may be abnormal
|
||||
// in large quantities. For example, a successful connection from an IP address
|
||||
// is normal. 10,000 connections from that same IP address is not normal. libp2p
|
||||
// itself does nothing besides emitting this log. Hook this up to another tool
|
||||
// like fail2ban to action on the log.
|
||||
func LogPeerStatus(sampleRate int, p peer.ID, peerAddr multiaddr.Multiaddr, keyVals ...string) {
|
||||
if rand.Intn(sampleRate) == 0 {
|
||||
keyValsStr := strings.Builder{}
|
||||
for i, kOrV := range keyVals {
|
||||
if i%2 == 0 {
|
||||
keyValsStr.WriteByte(' ')
|
||||
keyValsStr.WriteString(kOrV)
|
||||
keyValsStr.WriteByte('=')
|
||||
} else {
|
||||
keyValsStr.WriteString(kOrV)
|
||||
}
|
||||
}
|
||||
log.Infof("CANONICAL_PEER_STATUS: peer=%s addr=%s sample_rate=%v%s", p, peerAddr.String(), sampleRate, keyValsStr.String())
|
||||
}
|
||||
}
|
||||
|
@ -5,13 +5,21 @@ import (
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
logging "github.com/ipfs/go-log/v2"
|
||||
"github.com/libp2p/go-libp2p-core/test"
|
||||
"github.com/multiformats/go-multiaddr"
|
||||
)
|
||||
|
||||
func TestLogs(t *testing.T) {
|
||||
err := logging.SetLogLevel("canonical-log", "info")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
LogMisbehavingPeer(test.RandPeerIDFatal(t), multiaddr.StringCast("/ip4/1.2.3.4"), "somecomponent", fmt.Errorf("something"), "hi")
|
||||
|
||||
netAddr := &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 80}
|
||||
LogMisbehavingPeerNetAddr(test.RandPeerIDFatal(t), netAddr, "somecomponent", fmt.Errorf("something"), "hi")
|
||||
|
||||
LogPeerStatus(1, test.RandPeerIDFatal(t), multiaddr.StringCast("/ip4/1.2.3.4"), "extra", "info")
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user