Opt: color log

pull/44/head
zijiren233 2 years ago
parent 00ae5b93dc
commit 0cb732b0f7

@ -5,6 +5,7 @@ import (
"io" "io"
"log" "log"
"os" "os"
"time"
"github.com/natefinch/lumberjack" "github.com/natefinch/lumberjack"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -42,7 +43,12 @@ func InitLog(ctx context.Context) (err error) {
if err := l.Rotate(); err != nil { if err := l.Rotate(); err != nil {
logrus.Fatalf("log: rotate log file error: %v", err) logrus.Fatalf("log: rotate log file error: %v", err)
} }
var w io.Writer = colorable.NewNonColorableWriter(l) var w io.Writer
if forceColor {
w = colorable.NewNonColorableWriter(l)
} else {
w = l
}
if flags.Dev || flags.LogStd { if flags.Dev || flags.LogStd {
logrus.SetOutput(io.MultiWriter(os.Stdout, w)) logrus.SetOutput(io.MultiWriter(os.Stdout, w))
logrus.Infof("log: enable log to stdout and file: %s", conf.Conf.Log.FilePath) logrus.Infof("log: enable log to stdout and file: %s", conf.Conf.Log.FilePath)
@ -53,7 +59,9 @@ func InitLog(ctx context.Context) (err error) {
} }
switch conf.Conf.Log.LogFormat { switch conf.Conf.Log.LogFormat {
case "json": case "json":
logrus.SetFormatter(&logrus.JSONFormatter{}) logrus.SetFormatter(&logrus.JSONFormatter{
TimestampFormat: time.DateTime,
})
default: default:
if conf.Conf.Log.LogFormat != "text" { if conf.Conf.Log.LogFormat != "text" {
logrus.Warnf("unknown log format: %s, use default: text", conf.Conf.Log.LogFormat) logrus.Warnf("unknown log format: %s, use default: text", conf.Conf.Log.LogFormat)
@ -61,6 +69,12 @@ func InitLog(ctx context.Context) (err error) {
logrus.SetFormatter(&logrus.TextFormatter{ logrus.SetFormatter(&logrus.TextFormatter{
ForceColors: forceColor, ForceColors: forceColor,
DisableColors: !forceColor, DisableColors: !forceColor,
ForceQuote: flags.Dev,
DisableQuote: !flags.Dev,
DisableSorting: true,
FullTimestamp: true,
TimestampFormat: time.DateTime,
QuoteEmptyFields: true,
}) })
} }
log.SetOutput(logrus.StandardLogger().Writer()) log.SetOutput(logrus.StandardLogger().Writer())

@ -344,17 +344,18 @@ func GetUrlExtension(u string) string {
return strings.TrimLeft(filepath.Ext(p.Path), ".") return strings.TrimLeft(filepath.Ext(p.Path), ".")
} }
var needColor atomic.Pointer[bool] var (
needColor bool
needColorOnce sync.Once
)
func ForceColor() bool { func ForceColor() bool {
b := needColor.Load() needColorOnce.Do(func() {
if b == nil {
forceColor := colorable.IsTerminal(os.Stdout.Fd())
if flags.DisableLogColor { if flags.DisableLogColor {
forceColor = false needColor = false
} return
needColor.Store(&forceColor)
return forceColor
} }
return *b needColor = colorable.IsTerminal(os.Stdout.Fd())
})
return needColor
} }

Loading…
Cancel
Save