haiwai-grlogs/log.go
2020-05-06 14:32:26 +08:00

131 lines
2.6 KiB
Go

package grlogs
import (
"fmt"
"golib.gaore.com/GaoreGo/grlogs/logs"
"os"
"sync"
)
var loggers = sync.Map{}
var envkey = "CENTER_RUNMODE"
type Logger struct {
Lable string
*logs.BeeLogger
}
func (self *Logger) SetAdapter(level Level, adapter Adapter) *Logger {
if call, ok := adatperSetMapper[adapter]; ok {
if err := call(self, level); err != nil {
fmt.Println(err)
}
}
return self
}
func (self *Logger) DropAdapter(adapter Adapter) *Logger {
if call, ok := adatperDropMapper[adapter]; ok {
if err := call(self); err != nil {
fmt.Println(err)
}
}
return self
}
func New(label string, channelLens ...int64) (l *Logger, loaded bool) {
var channellens int64
var tmp interface{}
tmp, loaded = loggers.LoadOrStore(label, new(Logger))
l = tmp.(*Logger)
if len(channelLens) > 0 {
channellens = channelLens[0]
}
if !loaded {
l.Lable = label
l.BeeLogger = logs.NewLogger(channellens)
l.BeeLogger.Lable = label
l.Env = os.Getenv(envkey)
l.SetPrefix(fmt.Sprintf("[env:%s logger:%s]", os.Getenv(envkey), label))
l.EnableFuncCallDepth(true)
l.SetLogFuncCallDepth(2)
}
return
}
func Get(label string, channelLens ...int64) (l *Logger) {
var filelevel Level = LevelInfo
var loaded bool
if os.Getenv(envkey) == "dev" {
filelevel = LevelAll
}
if l, loaded = New(label, channelLens...); !loaded {
l.SetAdapter(filelevel, AdapterFile).SetAdapter(LevelAll, AdapterConsole)
}
return
}
func GetEs(label string, channelLens ...int64) (l *Logger) {
var filelevel Level = LevelInfo
var loaded bool
if os.Getenv(envkey) == "dev" {
filelevel = LevelAll
}
if l, loaded = New(label, channelLens...); !loaded {
l.SetAdapter(filelevel, AdapterFile).SetAdapter(LevelAll, AdapterConsole).SetAdapter(filelevel, AdapterElasticSearch)
}
return
}
func GetAli(label string, channelLens ...int64) (l *Logger) {
var filelevel Level = LevelInfo
var loaded bool
if os.Getenv(envkey) == "dev" {
filelevel = LevelAll
}
if l, loaded = New(label, channelLens...); !loaded {
l.SetAdapter(LevelAll, AdapterConsole).SetAdapter(filelevel, AdapterFile).SetAdapter(filelevel, AdapterAliLs)
}
return
}
func Close(lables ...string) {
wg := &sync.WaitGroup{}
for _, lable := range lables {
wg.Add(1)
go func() {
if v, ok := loggers.Load(lable); ok {
if tmp, ok := v.(*Logger); ok {
loggers.Delete(lable)
tmp.BeeLogger.Close()
}
}
wg.Done()
}()
}
wg.Wait()
}
func CloseAll() {
wg := &sync.WaitGroup{}
loggers.Range(func(key, value interface{}) bool {
wg.Add(1)
go func() {
if tmp, ok := value.(*Logger); ok {
tmp.BeeLogger.Close()
loggers.Delete(key)
}
wg.Done()
}()
return true
})
wg.Wait()
}