util.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package lib
  2. import (
  3. "log"
  4. "time"
  5. )
  6. const (
  7. LogTimeInterval = 5 * time.Second
  8. )
  9. type BytesLogger interface {
  10. AddOutbound(int)
  11. AddInbound(int)
  12. }
  13. // Default BytesLogger does nothing.
  14. type BytesNullLogger struct{}
  15. func (b BytesNullLogger) AddOutbound(amount int) {}
  16. func (b BytesNullLogger) AddInbound(amount int) {}
  17. // BytesSyncLogger uses channels to safely log from multiple sources with output
  18. // occuring at reasonable intervals.
  19. type BytesSyncLogger struct {
  20. outboundChan chan int
  21. inboundChan chan int
  22. }
  23. // NewBytesSyncLogger returns a new BytesSyncLogger and starts it loggin.
  24. func NewBytesSyncLogger() *BytesSyncLogger {
  25. b := &BytesSyncLogger{
  26. outboundChan: make(chan int, 5),
  27. inboundChan: make(chan int, 5),
  28. }
  29. go b.log()
  30. return b
  31. }
  32. func (b *BytesSyncLogger) log() {
  33. var outbound, inbound, outEvents, inEvents int
  34. ticker := time.NewTicker(LogTimeInterval)
  35. for {
  36. select {
  37. case <-ticker.C:
  38. if outEvents > 0 || inEvents > 0 {
  39. log.Printf("Traffic Bytes (in|out): %d | %d -- (%d OnMessages, %d Sends)",
  40. inbound, outbound, inEvents, outEvents)
  41. }
  42. outbound = 0
  43. outEvents = 0
  44. inbound = 0
  45. inEvents = 0
  46. case amount := <-b.outboundChan:
  47. outbound += amount
  48. outEvents++
  49. case amount := <-b.inboundChan:
  50. inbound += amount
  51. inEvents++
  52. }
  53. }
  54. }
  55. func (b *BytesSyncLogger) AddOutbound(amount int) {
  56. b.outboundChan <- amount
  57. }
  58. func (b *BytesSyncLogger) AddInbound(amount int) {
  59. b.inboundChan <- amount
  60. }