log_creator.go 1.5 KB

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