From 0cb732b0f7806e57a5f07482643601c0f3062f09 Mon Sep 17 00:00:00 2001 From: zijiren233 Date: Sun, 17 Dec 2023 19:46:20 +0800 Subject: [PATCH] Opt: color log --- internal/bootstrap/log.go | 22 ++++++++++++++++++---- utils/utils.go | 19 ++++++++++--------- 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/internal/bootstrap/log.go b/internal/bootstrap/log.go index 81188d0..651eb69 100644 --- a/internal/bootstrap/log.go +++ b/internal/bootstrap/log.go @@ -5,6 +5,7 @@ import ( "io" "log" "os" + "time" "github.com/natefinch/lumberjack" "github.com/sirupsen/logrus" @@ -42,7 +43,12 @@ func InitLog(ctx context.Context) (err error) { if err := l.Rotate(); err != nil { 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 { logrus.SetOutput(io.MultiWriter(os.Stdout, w)) logrus.Infof("log: enable log to stdout and file: %s", conf.Conf.Log.FilePath) @@ -53,14 +59,22 @@ func InitLog(ctx context.Context) (err error) { } switch conf.Conf.Log.LogFormat { case "json": - logrus.SetFormatter(&logrus.JSONFormatter{}) + logrus.SetFormatter(&logrus.JSONFormatter{ + TimestampFormat: time.DateTime, + }) default: if conf.Conf.Log.LogFormat != "text" { logrus.Warnf("unknown log format: %s, use default: text", conf.Conf.Log.LogFormat) } logrus.SetFormatter(&logrus.TextFormatter{ - ForceColors: forceColor, - DisableColors: !forceColor, + ForceColors: forceColor, + DisableColors: !forceColor, + ForceQuote: flags.Dev, + DisableQuote: !flags.Dev, + DisableSorting: true, + FullTimestamp: true, + TimestampFormat: time.DateTime, + QuoteEmptyFields: true, }) } log.SetOutput(logrus.StandardLogger().Writer()) diff --git a/utils/utils.go b/utils/utils.go index 16f8d60..39a0a74 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -344,17 +344,18 @@ func GetUrlExtension(u string) string { return strings.TrimLeft(filepath.Ext(p.Path), ".") } -var needColor atomic.Pointer[bool] +var ( + needColor bool + needColorOnce sync.Once +) func ForceColor() bool { - b := needColor.Load() - if b == nil { - forceColor := colorable.IsTerminal(os.Stdout.Fd()) + needColorOnce.Do(func() { if flags.DisableLogColor { - forceColor = false + needColor = false + return } - needColor.Store(&forceColor) - return forceColor - } - return *b + needColor = colorable.IsTerminal(os.Stdout.Fd()) + }) + return needColor }