gitee.com/liu-zhao234568/cntest@v1.0.0/les/flowcontrol/logger.go (about)

     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  
    17  package flowcontrol
    18  
    19  import (
    20  	"fmt"
    21  	"time"
    22  
    23  	"gitee.com/liu-zhao234568/cntest/common/mclock"
    24  )
    25  
    26  // logger collects events in string format and discards events older than the
    27  // "keep" parameter
    28  type logger struct {
    29  	events           map[uint64]logEvent
    30  	writePtr, delPtr uint64
    31  	keep             time.Duration
    32  }
    33  
    34  // logEvent describes a single event
    35  type logEvent struct {
    36  	time  mclock.AbsTime
    37  	event string
    38  }
    39  
    40  // newLogger creates a new logger
    41  func newLogger(keep time.Duration) *logger {
    42  	return &logger{
    43  		events: make(map[uint64]logEvent),
    44  		keep:   keep,
    45  	}
    46  }
    47  
    48  // add adds a new event and discards old events if possible
    49  func (l *logger) add(now mclock.AbsTime, event string) {
    50  	keepAfter := now - mclock.AbsTime(l.keep)
    51  	for l.delPtr < l.writePtr && l.events[l.delPtr].time <= keepAfter {
    52  		delete(l.events, l.delPtr)
    53  		l.delPtr++
    54  	}
    55  	l.events[l.writePtr] = logEvent{now, event}
    56  	l.writePtr++
    57  }
    58  
    59  // dump prints all stored events
    60  func (l *logger) dump(now mclock.AbsTime) {
    61  	for i := l.delPtr; i < l.writePtr; i++ {
    62  		e := l.events[i]
    63  		fmt.Println(time.Duration(e.time-now), e.event)
    64  	}
    65  }