并发读nil错针的问题

This commit is contained in:
liangzy 2020-05-15 18:33:47 +08:00
parent 3c03b5c497
commit cd85fd66ff
2 changed files with 26 additions and 5 deletions

18
log.go
View File

@ -14,6 +14,7 @@ var envkey = "CENTER_RUNMODE"
type Logger struct {
Lable string
*logs.BeeLogger
lock sync.RWMutex
}
func (self *Logger) SetAdapter(level Level, adapter Adapter) *Logger {
@ -34,17 +35,16 @@ func (self *Logger) DropAdapter(adapter Adapter) *Logger {
return self
}
func New(label string, channelLens ...int64) (l *Logger, loaded bool) {
func newLogger(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 {
tmp, loaded = loggers.LoadOrStore(label, func() *Logger {
l := &Logger{BeeLogger: logs.NewLogger(channellens)}
l.Lable = label
l.BeeLogger = logs.NewLogger(channellens)
l.BeeLogger.Lable = label
@ -52,10 +52,17 @@ func New(label string, channelLens ...int64) (l *Logger, loaded bool) {
l.SetPrefix(fmt.Sprintf("[env:%s logger:%s]", os.Getenv(envkey), label))
l.EnableFuncCallDepth(true)
l.SetLogFuncCallDepth(2)
}
return l
}())
l = tmp.(*Logger)
return
}
func New(label string, channelLens ...int64) (l *Logger, loaded bool) {
return newLogger(label, channelLens...)
}
func Get(label string, channelLens ...int64) (l *Logger) {
var filelevel Level = LevelInfo
var loaded bool
@ -78,6 +85,7 @@ func GetEs(label string, channelLens ...int64) (l *Logger) {
if l, loaded = New(label, channelLens...); !loaded {
l.SetAdapter(filelevel, AdapterFile).SetAdapter(LevelAll, AdapterConsole).SetAdapter(filelevel, AdapterElasticSearch)
l.lock.Unlock()
}
return
}

View File

@ -59,3 +59,16 @@ func TestDropAdapter(t *testing.T) {
Debug(errors.New("he hello"))
CloseAll()
}
func TestNew(t *testing.T) {
for i := 1; i < 10; i++ {
go func(i int) {
GetEs("ok").Debug("%d", i)
time.Sleep(1 * time.Second)
}(i)
}
for i := 1; i < 10; i++ {
GetEs("ok").Debug("aaaaaa%d", i)
}
}