logger.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2019 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package flowcontrol
  17. import (
  18. "fmt"
  19. "time"
  20. "github.com/ethereum/go-ethereum/common/mclock"
  21. )
  22. // logger collects events in string format and discards events older than the
  23. // "keep" parameter
  24. type logger struct {
  25. events map[uint64]logEvent
  26. writePtr, delPtr uint64
  27. keep time.Duration
  28. }
  29. // logEvent describes a single event
  30. type logEvent struct {
  31. time mclock.AbsTime
  32. event string
  33. }
  34. // newLogger creates a new logger
  35. func newLogger(keep time.Duration) *logger {
  36. return &logger{
  37. events: make(map[uint64]logEvent),
  38. keep: keep,
  39. }
  40. }
  41. // add adds a new event and discards old events if possible
  42. func (l *logger) add(now mclock.AbsTime, event string) {
  43. keepAfter := now - mclock.AbsTime(l.keep)
  44. for l.delPtr < l.writePtr && l.events[l.delPtr].time <= keepAfter {
  45. delete(l.events, l.delPtr)
  46. l.delPtr++
  47. }
  48. l.events[l.writePtr] = logEvent{now, event}
  49. l.writePtr++
  50. }
  51. // dump prints all stored events
  52. func (l *logger) dump(now mclock.AbsTime) {
  53. for i := l.delPtr; i < l.writePtr; i++ {
  54. e := l.events[i]
  55. fmt.Println(time.Duration(e.time-now), e.event)
  56. }
  57. }