log_creator.go 1.5 KB

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