gpt4 book ai didi

go - 记录到 stderr 和 stdout golang Google Cloud Platform

转载 作者:行者123 更新时间:2023-12-03 03:15:42 27 4
gpt4 key购买 nike

当前在 GCP 上运行 go 服务,但在日志查看器中,每条消息都被视为错误。

是否有根据日志级别记录到 stderr 和 stdout 的一般建议方法。即 stderr 的错误和 stdout 的其他任何内容。

我目前正在使用 logrus包并遇到过这个实现。我看到在仍然使用相同包的情况下实现此目的的其他方法是将记录器传递给需要它的每个包或创建一个全局日志对象,这两种方法我都不太热衷。

https://github.com/microsoft/fabrikate/pull/252/commits/bd24d62d7c2b851ad6e7b36653eb0a6dc364474b#diff-ed0770fdbf87b0c6d536e33a99a8df9c

最佳答案

您可以使用 GoLang 的 Stackdriver 库包:

go get -u cloud.google.com/go/logging

然后你就可以使用StandardLogger了:

// Sample stdlogging writes log.Logger logs to the Stackdriver Logging.
package main

import (
"context"
"log"

"cloud.google.com/go/logging"
)

func main() {
ctx := context.Background()

// Sets your Google Cloud Platform project ID.
projectID := "YOUR_PROJECT_ID"

// Creates a client.
client, err := logging.NewClient(ctx, projectID)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
defer client.Close()

// Sets the name of the log to write to.
logName := "my-log"

logger := client.Logger(logName).StandardLogger(logging.Info)

// Logs "hello world", log entry is visible at
// Stackdriver Logs.
logger.Println("hello world")
}

在这里您可以找到documentation on Google Cloud website

更新:


或者您可以尝试一下 GCP formatter for logrus

这不会将您的应用绑定(bind)到 Google Cloud Platform。但是,这并不意味着在另一个平台上您不需要更改代码来格式化输出。

使用 StackDriver 库是 Google Cloud 的推荐解决方案。

关于go - 记录到 stderr 和 stdout golang Google Cloud Platform,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57888588/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com