util.go 1.63 KB
Newer Older
1
package lib
2
3
4
5
6
7

import (
	"log"
	"time"
)

Serene Han's avatar
Serene Han committed
8
9
10
11
const (
	LogTimeInterval = 5
)

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
type BytesLogger interface {
	Log()
	AddOutbound(int)
	AddInbound(int)
}

// 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 {
28
29
30
31
32
33
34
	OutboundChan chan int
	InboundChan  chan int
	Outbound     int
	Inbound      int
	OutEvents    int
	InEvents     int
	IsLogging    bool
35
36
}

37
func (b *BytesSyncLogger) Log() {
38
	b.IsLogging = true
39
40
41
	var amount int
	output := func() {
		log.Printf("Traffic Bytes (in|out): %d | %d -- (%d OnMessages, %d Sends)",
42
43
44
45
46
			b.Inbound, b.Outbound, b.InEvents, b.OutEvents)
		b.Outbound = 0
		b.OutEvents = 0
		b.Inbound = 0
		b.InEvents = 0
47
48
49
50
	}
	last := time.Now()
	for {
		select {
51
52
53
		case amount = <-b.OutboundChan:
			b.Outbound += amount
			b.OutEvents++
Serene Han's avatar
Serene Han committed
54
			if time.Since(last) > time.Second*LogTimeInterval {
55
56
57
				last = time.Now()
				output()
			}
58
59
60
		case amount = <-b.InboundChan:
			b.Inbound += amount
			b.InEvents++
Serene Han's avatar
Serene Han committed
61
			if time.Since(last) > time.Second*LogTimeInterval {
62
63
64
				last = time.Now()
				output()
			}
Serene Han's avatar
Serene Han committed
65
		case <-time.After(time.Second * LogTimeInterval):
66
			if b.InEvents > 0 || b.OutEvents > 0 {
67
68
69
70
71
72
				output()
			}
		}
	}
}

73
func (b *BytesSyncLogger) AddOutbound(amount int) {
74
	if !b.IsLogging {
75
76
		return
	}
77
	b.OutboundChan <- amount
78
79
}

80
func (b *BytesSyncLogger) AddInbound(amount int) {
81
	if !b.IsLogging {
82
83
		return
	}
84
	b.InboundChan <- amount
85
}