github.com/sagernet/sing-box@v1.9.0-rc.20/log/log.go (about) 1 package log 2 3 import ( 4 "context" 5 "io" 6 "os" 7 "time" 8 9 "github.com/sagernet/sing-box/option" 10 E "github.com/sagernet/sing/common/exceptions" 11 ) 12 13 type Options struct { 14 Context context.Context 15 Options option.LogOptions 16 Observable bool 17 DefaultWriter io.Writer 18 BaseTime time.Time 19 PlatformWriter PlatformWriter 20 } 21 22 func New(options Options) (Factory, error) { 23 logOptions := options.Options 24 25 if logOptions.Disabled { 26 return NewNOPFactory(), nil 27 } 28 29 var logWriter io.Writer 30 var logFilePath string 31 32 switch logOptions.Output { 33 case "": 34 logWriter = options.DefaultWriter 35 if logWriter == nil { 36 logWriter = os.Stderr 37 } 38 case "stderr": 39 logWriter = os.Stderr 40 case "stdout": 41 logWriter = os.Stdout 42 default: 43 logFilePath = logOptions.Output 44 } 45 logFormatter := Formatter{ 46 BaseTime: options.BaseTime, 47 DisableColors: logOptions.DisableColor || logFilePath != "", 48 DisableTimestamp: !logOptions.Timestamp && logFilePath != "", 49 FullTimestamp: logOptions.Timestamp, 50 TimestampFormat: "-0700 2006-01-02 15:04:05", 51 } 52 factory := NewDefaultFactory( 53 options.Context, 54 logFormatter, 55 logWriter, 56 logFilePath, 57 options.PlatformWriter, 58 options.Observable, 59 ) 60 if logOptions.Level != "" { 61 logLevel, err := ParseLevel(logOptions.Level) 62 if err != nil { 63 return nil, E.Cause(err, "parse log level") 64 } 65 factory.SetLevel(logLevel) 66 } else { 67 factory.SetLevel(LevelTrace) 68 } 69 return factory, nil 70 }