sing-box/log/logrus.go

75 lines
1.9 KiB
Go
Raw Normal View History

2022-07-02 06:07:50 +00:00
package log
import (
"context"
"os"
2022-07-08 15:03:57 +00:00
"github.com/sagernet/sing-box/option"
2022-07-02 06:07:50 +00:00
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
F "github.com/sagernet/sing/common/format"
2022-07-06 07:01:09 +00:00
2022-07-02 06:07:50 +00:00
"github.com/sirupsen/logrus"
)
var _ Logger = (*logrusLogger)(nil)
type logrusLogger struct {
abstractLogrusLogger
2022-07-02 17:57:04 +00:00
outputPath string
output *os.File
2022-07-02 06:07:50 +00:00
}
type abstractLogrusLogger interface {
logrus.Ext1FieldLogger
WithContext(ctx context.Context) *logrus.Entry
}
func NewLogrusLogger(options option.LogOption) (*logrusLogger, error) {
logger := logrus.New()
logger.SetLevel(logrus.TraceLevel)
2022-07-04 08:45:32 +00:00
logger.SetFormatter(&LogrusTextFormatter{
DisableColors: options.DisableColor || options.Output != "",
DisableTimestamp: !options.Timestamp && options.Output != "",
FullTimestamp: options.Timestamp,
})
2022-07-02 06:07:50 +00:00
logger.AddHook(new(logrusHook))
var err error
if options.Level != "" {
logger.Level, err = logrus.ParseLevel(options.Level)
if err != nil {
return nil, err
}
}
2022-07-02 17:57:04 +00:00
return &logrusLogger{logger, options.Output, nil}, nil
}
func (l *logrusLogger) Start() error {
if l.outputPath != "" {
output, err := os.OpenFile(l.outputPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
2022-07-02 06:07:50 +00:00
if err != nil {
2022-07-02 17:57:04 +00:00
return E.Cause(err, "open log output")
2022-07-02 06:07:50 +00:00
}
2022-07-02 17:57:04 +00:00
l.abstractLogrusLogger.(*logrus.Logger).SetOutput(output)
2022-07-02 06:07:50 +00:00
}
2022-07-02 17:57:04 +00:00
return nil
}
func (l *logrusLogger) Close() error {
return common.Close(common.PtrOrNil(l.output))
2022-07-02 06:07:50 +00:00
}
func (l *logrusLogger) WithContext(ctx context.Context) Logger {
2022-07-02 17:57:04 +00:00
return &logrusLogger{abstractLogrusLogger: l.abstractLogrusLogger.WithContext(ctx)}
2022-07-02 06:07:50 +00:00
}
func (l *logrusLogger) WithPrefix(prefix string) Logger {
if entry, isEntry := l.abstractLogrusLogger.(*logrus.Entry); isEntry {
loadedPrefix := entry.Data["prefix"]
if loadedPrefix != "" {
prefix = F.ToString(loadedPrefix, prefix)
}
}
2022-07-02 17:57:04 +00:00
return &logrusLogger{abstractLogrusLogger: l.WithField("prefix", prefix)}
2022-07-02 06:07:50 +00:00
}