Browse Source

feat: get goroutine id using `goid`

dev
Dnomd343 11 months ago
parent
commit
07c247a491
  1. 1
      go.mod
  2. 2
      go.sum
  3. 18
      logger/encoder.go

1
go.mod

@ -18,6 +18,7 @@ require (
github.com/gookit/color v1.5.4 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/petermattis/goid v0.0.0-20231207134359-e60b3f734c67 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sys v0.10.0 // indirect

2
go.sum

@ -13,6 +13,8 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/petermattis/goid v0.0.0-20231207134359-e60b3f734c67 h1:jik8PHtAIsPlCRJjJzl4udgEf7hawInF9texMeO2jrU=
github.com/petermattis/goid v0.0.0-20231207134359-e60b3f734c67/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=

18
logger/encoder.go

@ -1,28 +1,16 @@
package logger
import (
"bytes"
"fmt"
"github.com/gookit/color"
"github.com/petermattis/goid"
"go.uber.org/zap/zapcore"
"path/filepath"
"runtime"
"strconv"
"strings"
"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
}
// getCaller calculate relative source path of caller.
func getCaller(ec zapcore.EntryCaller, verbose bool) string {
file, err := filepath.Rel(project, ec.File)
@ -57,7 +45,7 @@ func callerEncoder(ec zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("[" + getCaller(ec, false) + "]")
return
}
enc.AppendString(fmt.Sprintf("[%d] [%s]", getGid(), getCaller(ec, true)))
enc.AppendString(fmt.Sprintf("[%d] [%s]", goid.Get(), getCaller(ec, true)))
}
// callerColoredEncoder formats caller in square brackets with magenta color.
@ -68,7 +56,7 @@ func callerColoredEncoder(ec zapcore.EntryCaller, enc zapcore.PrimitiveArrayEnco
}
enc.AppendString(fmt.Sprintf(
"%s %s",
color.Blue.Render(fmt.Sprintf("[%d]", getGid())),
color.Blue.Render(fmt.Sprintf("[%d]", goid.Get())),
color.Magenta.Render("["+getCaller(ec, true)+"]"),
))
}

Loading…
Cancel
Save