Make BytesSyncLogger's implementation details internal.

Provide NewBytesSyncLogger that returns an opaque data structure.
Automatically start up the logging loop goroutine in NewBytesSyncLogger.
This commit is contained in:
David Fifield 2020-04-23 21:20:16 -06:00
parent 9a4e3e7bd9
commit 2853fc9362
2 changed files with 29 additions and 33 deletions

View file

@ -10,7 +10,6 @@ const (
)
type BytesLogger interface {
Log()
AddOutbound(int)
AddInbound(int)
}
@ -18,50 +17,55 @@ type BytesLogger interface {
// Default BytesLogger does nothing.
type BytesNullLogger struct{}
func (b BytesNullLogger) Log() {}
func (b BytesNullLogger) AddOutbound(amount int) {}
func (b BytesNullLogger) AddInbound(amount int) {}
// BytesSyncLogger uses channels to safely log from multiple sources with output
// occuring at reasonable intervals.
type BytesSyncLogger struct {
OutboundChan chan int
InboundChan chan int
Outbound int
Inbound int
OutEvents int
InEvents int
outboundChan chan int
inboundChan chan int
}
func (b *BytesSyncLogger) Log() {
var amount int
// NewBytesSyncLogger returns a new BytesSyncLogger and starts it loggin.
func NewBytesSyncLogger() *BytesSyncLogger {
b := &BytesSyncLogger{
outboundChan: make(chan int, 5),
inboundChan: make(chan int, 5),
}
go b.log()
return b
}
func (b *BytesSyncLogger) log() {
var outbound, inbound, outEvents, inEvents int
output := func() {
log.Printf("Traffic Bytes (in|out): %d | %d -- (%d OnMessages, %d Sends)",
b.Inbound, b.Outbound, b.InEvents, b.OutEvents)
b.Outbound = 0
b.OutEvents = 0
b.Inbound = 0
b.InEvents = 0
inbound, outbound, inEvents, outEvents)
outbound = 0
outEvents = 0
inbound = 0
inEvents = 0
}
last := time.Now()
for {
select {
case amount = <-b.OutboundChan:
b.Outbound += amount
b.OutEvents++
case amount := <-b.outboundChan:
outbound += amount
outEvents++
if time.Since(last) > time.Second*LogTimeInterval {
last = time.Now()
output()
}
case amount = <-b.InboundChan:
b.Inbound += amount
b.InEvents++
case amount := <-b.inboundChan:
inbound += amount
inEvents++
if time.Since(last) > time.Second*LogTimeInterval {
last = time.Now()
output()
}
case <-time.After(time.Second * LogTimeInterval):
if b.InEvents > 0 || b.OutEvents > 0 {
if inEvents > 0 || outEvents > 0 {
output()
}
}
@ -69,9 +73,9 @@ func (b *BytesSyncLogger) Log() {
}
func (b *BytesSyncLogger) AddOutbound(amount int) {
b.OutboundChan <- amount
b.outboundChan <- amount
}
func (b *BytesSyncLogger) AddInbound(amount int) {
b.InboundChan <- amount
b.inboundChan <- amount
}

View file

@ -161,15 +161,7 @@ func main() {
snowflakes.Tongue = sf.NewWebRTCDialer(broker, iceServers)
// Use a real logger to periodically output how much traffic is happening.
snowflakes.BytesLogger = &sf.BytesSyncLogger{
InboundChan: make(chan int, 5),
OutboundChan: make(chan int, 5),
Inbound: 0,
Outbound: 0,
InEvents: 0,
OutEvents: 0,
}
go snowflakes.BytesLogger.Log()
snowflakes.BytesLogger = sf.NewBytesSyncLogger()
go ConnectLoop(snowflakes)