36

[uber-zap/part4]自定义记录器

 5 years ago
source link: https://studygolang.com/articles/19407?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

说明

  • 之前翻译的一个教程(没有备份原地址,梯子被封了)。原地址找到后补上

正文

有时候,相比创建一个记录器,然后在函数中传递它,使用全局记录器会更方便

标准日志库 log 允许你使用 log.New() 创建自定义记录器,也可以调用帮助函数 log.Printf() 等直接使用标准记录器实例

zap使用 zap.L()zap.S() 提供这样的功能,但是对于我来说,不会直接使用它们。

你可以使用 zap.L() 访问全局标准记录器,这个函数返回共享记录器实例。加糖版本(sugared version)可以通过 zap.S() 访问

从我的简单使用中看到,这个共享记录器开箱即用--如果你只是立即使用它们,他们就不会提供输出。它们的唯一目的似乎是提供一种在代码中的任何位置检索此实例的简单方法

如果你确定要有用的使用此标准记录器,则需要使用 zap.ReplaceGlobals() 将记录器的核心替换为其他记录器的核心

func main() {
    fmt.Printf("\n*** Using the global logger out of box\n\n")

    zap.S().Infow("An INFO message", "iteration", 1)

    fmt.Printf("\n*** After replacing the global logger with a development logger\n\n")

    logger, _ := zap.NewDevelopment()
    zap.ReplaceGlobals(logger)

    zap.S().Infow("An INFO message", "iteration", 1)
}

输出

*** Using the global logger out of box


*** After replacing the global logger with a development logger

2018-11-01T10:08:10.017+0800    INFO    global_logger/main.go:19        An INFO message {"iteration": 1}

还有一种方法可以撤销全局记录器中的核心替换

func main() {
    fmt.Printf("\n*** After replacing the global logger with a development logger\n\n")
    logger, _ := zap.NewDevelopment()
    zap.ReplaceGlobals(logger)
    zap.S().Infow("An info message", "iteration", 1)

    fmt.Printf("\n*** After replacing the glboal logger with a production logger\n\n")
    logger, _ = zap.NewProduction()
    undo := zap.ReplaceGlobals(logger)
    zap.S().Infow("An info message", "iteration", 1)

    fmt.Printf("\n*** After replacing the glboal logger with a global logger\n\n")
    undo()    // 撤销
    zap.S().Infow("An info message", "iteration", 1)
}

输出

*** After replacing the global logger with a development logger

2018-11-01T10:39:34.555+0800    INFO    global_logger2/main.go:13       An info message {"iteration": 1}

*** After replacing the glboal logger with a production logger

{"level":"info","ts":1541039974.5559797,"caller":"global_logger2/main.go:18","msg":"An info message","iteration":1}

*** After replacing the glboal logger with a global logger

2018-11-01T10:39:34.556+0800    INFO    global_logger2/main.go:22       An info message {"iteration": 1}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK