log_creator.go 1.5 KB

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