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

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

Zap logger add UUID to all logs in golang

问题

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

import (
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func InitLogger() *zap.Logger {
	config := zap.NewProductionEncoderConfig()
	config.EncodeTime = zapcore.RFC3339TimeEncoder
	consoleEncoder := zapcore.NewJSONEncoder(config)
	core := zapcore.NewTee(zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), zapcore.InfoLevel))
	return zap.New(core).With()
}

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

var (
	log *zap.Logger
)

func init() {
	log = u.InitLogger()
}

func handler(r events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {

	out, err := exec.Command("uuidgen").Output()
	uuid := strings.ReplaceAll(string(out), "\n", "")
	if err != nil {
		log.Error(err.Error())
	}

	log.Info("PRINT_1", zap.Any("uuid", uuid), zap.Any("Request", r.Body))
}

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

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

英文:

I have this method used in a lambda:

import (
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func InitLogger() *zap.Logger {
	config := zap.NewProductionEncoderConfig()
	config.EncodeTime = zapcore.RFC3339TimeEncoder
	consoleEncoder := zapcore.NewJSONEncoder(config)
	core := zapcore.NewTee(zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), zapcore.InfoLevel))
	return zap.New(core).With()
}

And in my lambda Handler i have:

var (
	log *zap.Logger
)

func init() {
	log = u.InitLogger()
}

func handler(r events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {

	out, err := exec.Command("uuidgen").Output()
	uuid := strings.ReplaceAll(string(out), "\n", "")
	if err != nil {
		log.Error(err.Error())
	}

	log.Info("PRINT_1", zap.Any("uuid", uuid), zap.Any("Request", r.Body))
}

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,这意味着它是特定于请求的,而日志记录器是全局的...

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

例如:

func main() {
	logger := InitLogger(zap.String("foo", "bar"))
	logger.Info("First message with our `foo` key")
	logger.Info("Second message with our `foo` key")
}

func InitLogger(fields ...zap.Field) *zap.Logger {
	config := zap.NewProductionEncoderConfig()
	config.EncodeTime = zapcore.RFC3339TimeEncoder
	consoleEncoder := zapcore.NewJSONEncoder(config)
	core := zapcore.NewTee(zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), zapcore.InfoLevel))
	return zap.New(core).With(fields...)
}

输出:

{"level":"info","ts":"2022-11-24T18:30:45+01:00","msg":"First message with our `foo` key","foo":"bar"}
{"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:

func main() {
	logger := InitLogger(zap.String("foo", "bar"))
	logger.Info("First message with our `foo` key")
	logger.Info("Second message with our `foo` key")
}

func InitLogger(fields ...zap.Field) *zap.Logger {
	config := zap.NewProductionEncoderConfig()
	config.EncodeTime = zapcore.RFC3339TimeEncoder
	consoleEncoder := zapcore.NewJSONEncoder(config)
	core := zapcore.NewTee(zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), zapcore.InfoLevel))
	return zap.New(core).With(fields...)
}

Output:

{"level":"info","ts":"2022-11-24T18:30:45+01:00","msg":"First message with our `foo` key","foo":"bar"}
{"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:

确定