From d6123a14e96879770f4fb1523c185840f4cf031c Mon Sep 17 00:00:00 2001 From: Dnomd343 Date: Sat, 9 Sep 2023 22:55:55 +0800 Subject: [PATCH] feat: show goroutine id in log --- next/logger/encoder.go | 30 ++++++++++++++++++++++++++++-- next/logger/logger.go | 2 ++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/next/logger/encoder.go b/next/logger/encoder.go index f7e69e4..4cacc8a 100644 --- a/next/logger/encoder.go +++ b/next/logger/encoder.go @@ -1,12 +1,26 @@ package logger import ( + "bytes" "fmt" "github.com/gookit/color" "go.uber.org/zap/zapcore" + "runtime" + "strconv" "time" ) +// getGID get goroutine ID only for debugging. +// -> https://blog.sgmansfield.com/2015/12/goroutine-ids/ +func getGID() uint64 { + b := make([]byte, 64) + b = b[:runtime.Stack(b, false)] + b = bytes.TrimPrefix(b, []byte("goroutine ")) + b = b[:bytes.IndexByte(b, ' ')] + n, _ := strconv.ParseUint(string(b), 10, 64) + return n +} + // timeEncoder formats the time as a string. func timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { enc.AppendString(t.Format("2006-01-02 15:04:05.000")) @@ -24,13 +38,25 @@ func timeColoredEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { // callerEncoder formats caller in square brackets. func callerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) { - enc.AppendString("[" + caller.TrimmedPath() + "]") + if !handle.gid { + enc.AppendString("[" + caller.TrimmedPath() + "]") + } else { + enc.AppendString(fmt.Sprintf("[%s] [%d]", caller.TrimmedPath(), getGID())) + } } // callerColoredEncoder formats caller in square brackets // with magenta color. func callerColoredEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) { - enc.AppendString(color.Magenta.Render("[" + caller.TrimmedPath() + "]")) + if !handle.gid { + enc.AppendString(color.Magenta.Render("[" + caller.TrimmedPath() + "]")) + return + } + enc.AppendString(fmt.Sprintf( + "%s %s", + color.Magenta.Render("["+caller.TrimmedPath()+"]"), + color.Blue.Render(fmt.Sprintf("[%d]", getGID())), + )) } // levelEncoder formats log level using square brackets. diff --git a/next/logger/logger.go b/next/logger/logger.go index 15b5fd3..f57fbff 100644 --- a/next/logger/logger.go +++ b/next/logger/logger.go @@ -7,6 +7,7 @@ import ( ) type Logger struct { + gid bool logger *zap.Logger level *zap.AtomicLevel sugar *zap.SugaredLogger @@ -44,6 +45,7 @@ func init() { ) logger := zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1)) handle = Logger{ + gid: true, logger: logger, level: &level, sugar: logger.Sugar(),