From 5ca6d6a5212b43069a43f868b0b9073f1d12790b Mon Sep 17 00:00:00 2001 From: Dnomd343 Date: Tue, 6 Feb 2024 21:51:35 +0800 Subject: [PATCH] perf: update logger encoder --- logger/encoder.go | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/logger/encoder.go b/logger/encoder.go index 2aa0e43..a190ca5 100644 --- a/logger/encoder.go +++ b/logger/encoder.go @@ -1,7 +1,6 @@ package logger import ( - "fmt" "github.com/gookit/color" "github.com/petermattis/goid" "go.uber.org/zap/zapcore" @@ -11,6 +10,11 @@ import ( "time" ) +// / getGid return goroutine id with string. +func getGid() string { + return strconv.FormatInt(goid.Get(), 10) +} + // getCaller calculate relative source path of caller. func getCaller(ec zapcore.EntryCaller, verbose bool) string { file, err := filepath.Rel(project, ec.File) @@ -32,33 +36,28 @@ func timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { // timeColoredEncoder formats the time as a colored string // with custom prefix. func timeColoredEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { - enc.AppendString(fmt.Sprintf( - "%s %s", - color.Cyan.Render(logger.prefix), // colored prefix - color.Gray.Render(t.Format("2006-01-02 15:04:05.000")), - )) + enc.AppendString(color.Cyan.Render(logger.prefix)) + enc.AppendString(color.Gray.Render(t.Format("2006-01-02 15:04:05.000"))) } // callerEncoder formats caller in square brackets. func callerEncoder(ec zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) { - if !logger.verbose { + if logger.verbose { + enc.AppendString("[" + getGid() + "]") + enc.AppendString("[" + getCaller(ec, true) + "]") + } else { enc.AppendString("[" + getCaller(ec, false) + "]") - return } - enc.AppendString(fmt.Sprintf("[%d] [%s]", goid.Get(), getCaller(ec, true))) } // callerColoredEncoder formats caller in square brackets with magenta color. func callerColoredEncoder(ec zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) { - if !logger.verbose { + if logger.verbose { + enc.AppendString(color.Blue.Render("[" + getGid() + "]")) + enc.AppendString(color.Magenta.Render("[" + getCaller(ec, true) + "]")) + } else { enc.AppendString(color.Magenta.Render("[" + getCaller(ec, false) + "]")) - return } - enc.AppendString(fmt.Sprintf( - "%s %s", - color.Blue.Render(fmt.Sprintf("[%d]", goid.Get())), - color.Magenta.Render("["+getCaller(ec, true)+"]"), - )) } // levelEncoder formats log level using square brackets.