github.com/moqsien/xraycore@v1.8.5/app/log/log_creator.go (about) 1 package log 2 3 import ( 4 "sync" 5 6 "github.com/moqsien/xraycore/common" 7 "github.com/moqsien/xraycore/common/log" 8 ) 9 10 type HandlerCreatorOptions struct { 11 Path string 12 } 13 14 type HandlerCreator func(LogType, HandlerCreatorOptions) (log.Handler, error) 15 16 var handlerCreatorMap = make(map[LogType]HandlerCreator) 17 18 var handlerCreatorMapLock = &sync.RWMutex{} 19 20 func RegisterHandlerCreator(logType LogType, f HandlerCreator) error { 21 if f == nil { 22 return newError("nil HandlerCreator") 23 } 24 25 handlerCreatorMapLock.Lock() 26 defer handlerCreatorMapLock.Unlock() 27 28 handlerCreatorMap[logType] = f 29 return nil 30 } 31 32 func createHandler(logType LogType, options HandlerCreatorOptions) (log.Handler, error) { 33 handlerCreatorMapLock.RLock() 34 defer handlerCreatorMapLock.RUnlock() 35 36 creator, found := handlerCreatorMap[logType] 37 if !found { 38 return nil, newError("unable to create log handler for ", logType) 39 } 40 return creator(logType, options) 41 } 42 43 func init() { 44 common.Must(RegisterHandlerCreator(LogType_Console, func(lt LogType, options HandlerCreatorOptions) (log.Handler, error) { 45 return log.NewLogger(log.CreateStdoutLogWriter()), nil 46 })) 47 48 common.Must(RegisterHandlerCreator(LogType_File, func(lt LogType, options HandlerCreatorOptions) (log.Handler, error) { 49 creator, err := log.CreateFileLogWriter(options.Path) 50 if err != nil { 51 return nil, err 52 } 53 return log.NewLogger(creator), nil 54 })) 55 56 common.Must(RegisterHandlerCreator(LogType_None, func(lt LogType, options HandlerCreatorOptions) (log.Handler, error) { 57 return nil, nil 58 })) 59 }