github.com/GuanceCloud/cliutils@v1.1.21/logger/slogger.go (about) 1 // Unless explicitly stated otherwise all files in this repository are licensed 2 // under the MIT License. 3 // This product includes software developed at Guance Cloud (https://www.guance.com/). 4 // Copyright 2021-present Guance, Inc. 5 6 package logger 7 8 import ( 9 "sync" 10 "sync/atomic" 11 12 "go.uber.org/zap" 13 ) 14 15 var ( 16 totalSloggers int64 17 slogs = &sync.Map{} 18 ) 19 20 func SLogger(name string) *Logger { 21 if root == nil && defaultStdoutRootLogger == nil { 22 panic("should not been here: root logger not set") 23 } 24 25 return &Logger{SugaredLogger: slogger(name)} 26 } 27 28 func DefaultSLogger(name string) *Logger { 29 return &Logger{SugaredLogger: slogger(name)} 30 } 31 32 func TotalSLoggers() int64 { 33 return atomic.LoadInt64(&totalSloggers) 34 } 35 36 func slogger(name string) *zap.SugaredLogger { 37 r := root // prefer root logger 38 39 if r == nil { 40 r = defaultStdoutRootLogger 41 } 42 43 if r == nil { 44 panic("should not been here") 45 } 46 47 newlog := getSugarLogger(r, name) 48 if root != nil { 49 l, loaded := slogs.LoadOrStore(name, newlog) 50 if !loaded { 51 atomic.AddInt64(&totalSloggers, 1) 52 } 53 54 return l.(*zap.SugaredLogger) 55 } 56 57 return newlog 58 } 59 60 func getSugarLogger(l *zap.Logger, name string) *zap.SugaredLogger { 61 return l.Sugar().Named(name) 62 }