util.go 1.5 KB

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