我正在try 将我的应用程序从漂亮的Logrus(对调试非常有帮助)中迁移出来,并引入Uber日志(log)框架Zap.

使用Logrus,我只能初始化记录器一次,然后从其他GO文件中重用它,例如:

package main
import(
    // Print filename on log
    filename "github.com/onrik/logrus/filename"
    // Very nice log library
    log "github.com/sirupsen/logrus"
)

func main(){

// ==== SET LOGGING
    Formatter := new(log.TextFormatter)
    Formatter.TimestampFormat = "Jan _2 15:04:05.000000000"
    Formatter.FullTimestamp = true
    Formatter.ForceColors = true
    log.AddHook(filename.NewHook()) // Print filename + line at every log
    log.SetFormatter(Formatter)

}

从其他GO文件中,我可以在不进行任何其他初始化情况下重用记录器:

// VerifyCommandLineInput is delegated to manage the inputer parameter provide with the input flag from command line
func VerifyCommandLineInput() datastructures.Configuration {
    log.Debug("VerifyCommandLineInput | Init a new configuration from the conf file")
    c := flag.String("config", "./conf/test.json", "Specify the configuration file.")
    flag.Parse()
    if strings.Compare(*c, "") == 0 {
        log.Fatal("VerifyCommandLineInput | Call the tool using --config conf/config.json")
    }
    file, err := os.Open(*c)
    if err != nil {
        log.Fatal("VerifyCommandLineInput | can't open config file: ", err)
    }
    defer file.Close()
    decoder := json.NewDecoder(file)
    cfg := datastructures.Configuration{}
    err = decoder.Decode(&cfg)
    if err != nil {
        log.Fatal("VerifyCommandLineInput | can't decode config JSON: ", err)
    }
    log.Debug("VerifyCommandLineInput | Conf loaded -> ", cfg)

    return cfg
}

我的问题是:使用Zap日志(log)框架,我如何初始化主函数中的日志(log)并从其他GO文件使用该记录器?

推荐答案

您可以在main函数中设置记录器,然后调用zap.ReplaceGlobals将其用作默认的全局记录器.

ReplaceGlobals替换全局Logger和SugardLogger,并返回一个函数以恢复原始值.它可以安全地同时使用.

Go相关问答推荐

追加一个字节数组的分配比2个字节数组的分配要少得多

向API网关终结点发出POST请求时出现AWS Lambda With Go:";Rune me.InvalidEntrypoint";错误

为什么Slices包中的函数定义Slice参数的类型参数?

exec的可执行决议.命令+路径

如果第一次匹配条件,如何跳过切片中的值

Go 中带有回调的 MiniDumpWriteDump

在多个 struct 体中重用 Go 中的函数

使用Go和Operator SDK通过API调用设置Kubernetes Pods的安装步骤

带有前导零的整数参数被 flag.IntVar 解析为八进制

Kubo,来自 IpfsNode.Bootstrap 的无效内存地址或零指针取消引用

如何以干净的方式在中间件中注入 repo 或服务?

MQTT 客户端没有收到另一个客户端发送的消息

Gremlin-Go:树步骤不可序列化

如何将 base64 编码的公钥转换为 crypto.PublicKey 或 ecdsa.PublicKey

使用 Grafana alert 在几分钟内重复alert

如何将多个切片打印为一个切片?

如何 Select 前 N 个元素 Gin-Gorm

为什么 Go 中的 maps.Keys() 将 map 类型指定为 M?

如何解决在mac m1中运行gcc失败退出状态1?

如何正确解组不同类型的数组?