日志中的 Uber Zap 记录器函数名称

Uber Zap logger function name in logs

如何从 Uber Zap 日志中获取打印在日志中的函数名称? 这是 PR request 他们似乎添加了在日志中输出函数名称的功能。

我正在使用 golang 版本 1.15 和 go.uber.org/zap v1.16.0

这是我的代码:

package main

import (
    "go.uber.org/zap"
)

var logger *zap.Logger

func main() {
    logger := NewLogger()
    logger.Info("Test msg Main")
    TestFunc(logger)
}

func TestFunc(logger *zap.Logger)  {
    logger.Info("Test msg TestFunc")
}

func NewLogger() *zap.Logger {
    config := zap.NewDevelopmentConfig()
    opts := []zap.Option{
        zap.AddCallerSkip(1), // traverse call depth for more useful log lines
        zap.AddCaller(),
    }

    logger, _ = config.Build(opts...)
    return logger
}

这是我得到的输出 with/without 添加 AddCaller() 选项

2021-03-01T15:00:02.927-0800    INFO    runtime/proc.go:204     Test msg Main
2021-03-01T15:00:02.927-0800    INFO    cmd/main.go:12  Test msg TestFunc

我期待

   2021-03-01T15:00:02.927-0800    INFO    runtime/proc.go:204   main  Test msg Main
   2021-03-01T15:00:02.927-0800    INFO    cmd/main.go:12  TestFunc Test msg TestFunc

默认情况下,提供的编码器预设 (NewDevelopmentEncoderConfig used by NewDevelopmentConfig and NewProductionEncoderConfig used by NewProductionConfig) 不启用函数名称记录。

要启用函数名称,您需要启用调用者(默认为true)config.EncoderConfig.FunctionKey设置一个非空值。

来源:EncoderConfig

type EncoderConfig struct {
    // Set the keys used for each log entry. If any key is empty, that portion
    // of the entry is omitted.
    ...
    CallerKey     string `json:"callerKey" yaml:"callerKey"`
    FunctionKey   string `json:"functionKey" yaml:"functionKey"` // this needs to be set
    StacktraceKey string `json:"stacktraceKey" yaml:"stacktraceKey"`
    ...
}

示例控制台记录器:

func main() {
    config := zap.NewDevelopmentConfig()
    // if you're using console encoding, the FunctionKey value can be any
    // non-empty string because console encoding does not print the key.
    config.EncoderConfig.FunctionKey = "F"
    logger, _ := config.Build()
    logger.Info("Test Logging")
    // Output: 2021-03-03T11:41:47.728+0800    INFO    example/main.go:11     main.main       Test Logging
}

示例JSON记录器:

func main() {
    config := zap.NewProductionConfig()
    // the FunctionKey value matters because it will become the JSON field
    config.EncoderConfig.FunctionKey = "func"
    logger, _ := config.Build()
    log(logger)
    // Output: {"level":"info","ts":1614743088.538128,"caller":"example/main.go:15","func":"main.log","msg":"Test Logging"}
}

func log(logger *zap.Logger) {
    logger.Info("Test Logging")
}