AFAIRE
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
logger/manager.go

114 lines
2.1 KiB

/*
------------------------------------------------------------------------------------------------------------------------
####### logger ####### Copyright (c) 2021-2022 losyme ############################################## MIT License #######
------------------------------------------------------------------------------------------------------------------------
*/
package logger
import (
"sync"
"forge.chapril.org/losyme/errors"
"forge.chapril.org/losyme/zombie"
)
const _logChanSize = 64
var _manager = newManager()
type manager struct {
loggers map[string]*Logger
mutex sync.Mutex
logChannel chan *Log
logHandler func(*Log)
zombie *zombie.Group
}
func newManager() *manager {
m := &manager{
loggers: make(map[string]*Logger),
}
m.logHandler = m.sync
return m
}
func (m *manager) register(l *Logger) error {
m.mutex.Lock()
defer m.mutex.Unlock()
ll, ok := m.loggers[l.id]
if ok {
return errors.New( /////////////////////////////////////////////////////////////////////////////////////////////
"a logger with the same id already exists",
"id", l.id,
"name", ll.name,
)
}
m.loggers[l.id] = l
return nil
}
func (m *manager) unregister(id string) {
m.mutex.Lock()
delete(m.loggers, id)
m.mutex.Unlock()
}
func (m *manager) sync(log *Log) {
m.mutex.Lock()
_ = log.Logger.output.Log(log)
_logPool.Put(log)
m.mutex.Unlock()
}
func (m *manager) async(log *Log) {
m.logChannel <- log
}
func (m *manager) start() {
if m.zombie != nil {
return
}
m.logChannel = make(chan *Log, _logChanSize)
m.logHandler = m.async
m.zombie = zombie.Go( //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1,
func(_ int) {
for log := range m.logChannel {
_ = log.Logger.output.Log(log)
_logPool.Put(log)
}
},
)
}
func (m *manager) stop() {
if m.zombie == nil {
return
}
close(m.logChannel)
m.zombie.Wait()
}
func Start() {
_manager.start()
}
func Stop() {
_manager.stop()
}
/*
######################################################################################################## @(°_°)@ #######
*/