{ "@context": "https://schema.org", "@type": "Article", "headline": "使用 UUID 来追踪和标识 Golang 中的日志记录", "datePublished": "2024-02-08T17:27:22", "dateModified": "2024-02-08T17:27:22", "description": "学习Golang要努力,但是不要急!今天的这篇文章《使用 UUID 来追踪和标识 Golang 中的日志记录》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!问题内容我在 lambda 中使用了这个方法:import ( os go.uber.org/zap go.uber.org/zap/zapcore)func initlogger() *zap.logger { config := zap.newpr", "publisher": { "@type": "Organization", "name": "Golang学习网", "url": "https://m.17golang.com" }, "mainEntityOfPage": { "@type": "WebPage", "@id": "https://m.17golang.com/article/94790.html" } }
登录
首页 >  Golang >  Go问答

使用 UUID 来追踪和标识 Golang 中的日志记录

来源:stackoverflow

时间:2024-02-08 17:27:22 421浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《使用 UUID 来追踪和标识 Golang 中的日志记录》将会介绍到等等知识点,如果你想深入学习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 作为参数传递给所有方法,以将其打印在日志信息或错误中。


正确答案


您将不得不稍微重新安排您的代码,因为您只是在处理程序中创建 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"}

以上就是《使用 UUID 来追踪和标识 Golang 中的日志记录》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>