在golang中,将UUID添加到所有日志中的Zap记录器。

huangapple go评论111阅读模式
英文:

Zap logger add UUID to all logs in golang

问题

我有一个在lambda中使用的方法:

  1. import (
  2. "os"
  3. "go.uber.org/zap"
  4. "go.uber.org/zap/zapcore"
  5. )
  6. func InitLogger() *zap.Logger {
  7. config := zap.NewProductionEncoderConfig()
  8. config.EncodeTime = zapcore.RFC3339TimeEncoder
  9. consoleEncoder := zapcore.NewJSONEncoder(config)
  10. core := zapcore.NewTee(zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), zapcore.InfoLevel))
  11. return zap.New(core).With()
  12. }

在我的lambda处理程序中,我有:

  1. var (
  2. log *zap.Logger
  3. )
  4. func init() {
  5. log = u.InitLogger()
  6. }
  7. func handler(r events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
  8. out, err := exec.Command("uuidgen").Output()
  9. uuid := strings.ReplaceAll(string(out), "\n", "")
  10. if err != nil {
  11. log.Error(err.Error())
  12. }
  13. log.Info("PRINT_1", zap.Any("uuid", uuid), zap.Any("Request", r.Body))
  14. }

我有一个问题,是否可以在不逐个添加的情况下将UUID添加到所有日志中?因为在每个需要打印的日志中,我都需要添加zap.Any("uuid", uuid)

问题是我需要将UUID作为参数传递给所有方法,以便在日志信息或错误中打印它。

英文:

I have this method used in a lambda:

  1. import (
  2. "os"
  3. "go.uber.org/zap"
  4. "go.uber.org/zap/zapcore"
  5. )
  6. func InitLogger() *zap.Logger {
  7. config := zap.NewProductionEncoderConfig()
  8. config.EncodeTime = zapcore.RFC3339TimeEncoder
  9. consoleEncoder := zapcore.NewJSONEncoder(config)
  10. core := zapcore.NewTee(zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), zapcore.InfoLevel))
  11. return zap.New(core).With()
  12. }

And in my lambda Handler i have:

  1. var (
  2. log *zap.Logger
  3. )
  4. func init() {
  5. log = u.InitLogger()
  6. }
  7. func handler(r events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
  8. out, err := exec.Command("uuidgen").Output()
  9. uuid := strings.ReplaceAll(string(out), "\n", "")
  10. if err != nil {
  11. log.Error(err.Error())
  12. }
  13. log.Info("PRINT_1", zap.Any("uuid", uuid), zap.Any("Request", r.Body))
  14. }

I have a question, is possible add the UUID to all logs without adding one by one?, because in each log that I need print something, I need add zap.Any("uuid", uuid)

The problem is that I need pass as parameter to all methods the UUID to print it in the log info, or error.

答案1

得分: 0

你需要稍微调整一下你的代码,因为你只是在处理程序中创建了UUID,这意味着它是特定于请求的,而日志记录器是全局的...

但是,针对该库的要点是,你必须创建一个子记录器(实际上你已经在做了:你只需要将字段传递给它)。任何后续对子记录器的日志写入都将包含这些字段。

例如:

  1. func main() {
  2. logger := InitLogger(zap.String("foo", "bar"))
  3. logger.Info("First message with our `foo` key")
  4. logger.Info("Second message with our `foo` key")
  5. }
  6. func InitLogger(fields ...zap.Field) *zap.Logger {
  7. config := zap.NewProductionEncoderConfig()
  8. config.EncodeTime = zapcore.RFC3339TimeEncoder
  9. consoleEncoder := zapcore.NewJSONEncoder(config)
  10. core := zapcore.NewTee(zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), zapcore.InfoLevel))
  11. return zap.New(core).With(fields...)
  12. }

输出:

  1. {"level":"info","ts":"2022-11-24T18:30:45+01:00","msg":"First message with our `foo` key","foo":"bar"}
  2. {"level":"info","ts":"2022-11-24T18:30:45+01:00","msg":"Second message with our `foo` key","foo":"bar"}
英文:

You will have to slightly re-arrange your code since you're only creating the UUID in the handler, which implies it's request-specific whilst the logger is global...

But the gist, specific to the library, is that you've got to create a child logger (which you are, in fact, already doing: you just need to pass the fields there). Any subsequent log writes to the child logger will include those fields.

For example:

  1. func main() {
  2. logger := InitLogger(zap.String("foo", "bar"))
  3. logger.Info("First message with our `foo` key")
  4. logger.Info("Second message with our `foo` key")
  5. }
  6. func InitLogger(fields ...zap.Field) *zap.Logger {
  7. config := zap.NewProductionEncoderConfig()
  8. config.EncodeTime = zapcore.RFC3339TimeEncoder
  9. consoleEncoder := zapcore.NewJSONEncoder(config)
  10. core := zapcore.NewTee(zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), zapcore.InfoLevel))
  11. return zap.New(core).With(fields...)
  12. }

Output:

  1. {"level":"info","ts":"2022-11-24T18:30:45+01:00","msg":"First message with our `foo` key","foo":"bar"}
  2. {"level":"info","ts":"2022-11-24T18:30:45+01:00","msg":"Second message with our `foo` key","foo":"bar"}

huangapple
  • 本文由 发表于 2022年11月25日 01:17:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/74564325.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定