sing-box/log/log.go

71 lines
1.4 KiB
Go
Raw Normal View History

2023-04-03 10:24:20 +00:00
package log
import (
2023-04-21 09:29:00 +00:00
"context"
2023-04-03 10:24:20 +00:00
"io"
"os"
"time"
"github.com/sagernet/sing-box/option"
E "github.com/sagernet/sing/common/exceptions"
)
type Options struct {
2023-04-21 09:29:00 +00:00
Context context.Context
2023-04-03 10:24:20 +00:00
Options option.LogOptions
Observable bool
DefaultWriter io.Writer
BaseTime time.Time
2023-11-15 05:05:33 +00:00
PlatformWriter PlatformWriter
2023-04-03 10:24:20 +00:00
}
func New(options Options) (Factory, error) {
logOptions := options.Options
if logOptions.Disabled {
return NewNOPFactory(), nil
}
var logWriter io.Writer
var logFilePath string
2023-04-03 10:24:20 +00:00
switch logOptions.Output {
case "":
logWriter = options.DefaultWriter
if logWriter == nil {
logWriter = os.Stderr
}
case "stderr":
logWriter = os.Stderr
case "stdout":
logWriter = os.Stdout
default:
logFilePath = logOptions.Output
2023-04-03 10:24:20 +00:00
}
logFormatter := Formatter{
BaseTime: options.BaseTime,
DisableColors: logOptions.DisableColor || logFilePath != "",
DisableTimestamp: !logOptions.Timestamp && logFilePath != "",
2023-04-03 10:24:20 +00:00
FullTimestamp: logOptions.Timestamp,
TimestampFormat: "-0700 2006-01-02 15:04:05",
}
factory := NewDefaultFactory(
options.Context,
logFormatter,
logWriter,
logFilePath,
options.PlatformWriter,
options.Observable,
)
2023-04-03 10:24:20 +00:00
if logOptions.Level != "" {
logLevel, err := ParseLevel(logOptions.Level)
if err != nil {
return nil, E.Cause(err, "parse log level")
}
factory.SetLevel(logLevel)
} else {
factory.SetLevel(LevelTrace)
}
return factory, nil
}