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