github.com/xxf098/lite-proxy@v0.15.1-0.20230422081941-12c69f323218/stats/stats.go (about)

     1  package stats
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  )
     7  
     8  const (
     9  	UpProxy   = "outbound>>>proxy>>>traffic>>>uplink"
    10  	DownProxy = "outbound>>>proxy>>>traffic>>>downlink"
    11  )
    12  
    13  var DefaultManager *Manager = nil
    14  
    15  func init() {
    16  	DefaultManager = &Manager{
    17  		counters: make(map[string]*Counter, 2),
    18  	}
    19  	DefaultManager.counters[UpProxy] = new(Counter)
    20  	DefaultManager.counters[DownProxy] = new(Counter)
    21  }
    22  
    23  type Manager struct {
    24  	access   sync.RWMutex
    25  	counters map[string]*Counter
    26  	running  bool
    27  }
    28  
    29  // NewManager creates an instance of Statistics Manager.
    30  func NewManager() (*Manager, error) {
    31  	m := &Manager{
    32  		counters: make(map[string]*Counter),
    33  	}
    34  
    35  	return m, nil
    36  }
    37  
    38  // RegisterCounter implements stats.Manager.
    39  func (m *Manager) RegisterCounter(name string) (*Counter, error) {
    40  	m.access.Lock()
    41  	defer m.access.Unlock()
    42  
    43  	if _, found := m.counters[name]; found {
    44  		return nil, fmt.Errorf("counter %s already registered", name)
    45  	}
    46  	// newError("create new counter ", name).AtDebug().WriteToLog()
    47  	c := new(Counter)
    48  	m.counters[name] = c
    49  	return c, nil
    50  }
    51  
    52  func (m *Manager) UnregisterCounter(name string) error {
    53  	m.access.Lock()
    54  	defer m.access.Unlock()
    55  
    56  	if _, found := m.counters[name]; found {
    57  		// newError("remove counter ", name).AtDebug().WriteToLog()
    58  		delete(m.counters, name)
    59  	}
    60  	return nil
    61  }
    62  
    63  func (m *Manager) GetCounter(name string) *Counter {
    64  	m.access.RLock()
    65  	defer m.access.RUnlock()
    66  
    67  	if c, found := m.counters[name]; found {
    68  		return c
    69  	}
    70  	return nil
    71  }