log_creator.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // +build !confonly
  2. package log
  3. import (
  4. "sync"
  5. "github.com/v2fly/v2ray-core/v4/common"
  6. "github.com/v2fly/v2ray-core/v4/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 newError("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, newError("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. }