3

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

我正在使用 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
}

这是我在添加/不添加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
4

1 回答 1

5

默认情况下,提供的编码器预设(NewDevelopmentConfig使用的NewDevelopmentEncoderConfigNewProductionConfig使用的NewProductionEncoderConfig)不启用函数名称日志记录。

要启用函数名,您需要启用 caller(默认为 true)config.EncoderConfig.FunctionKey.

来源:编码器配置

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")
}
于 2021-03-03T03:54:01.787 回答