jwt*_*tea 5 logging go google-cloud-platform
当前在 GCP 上运行 go 服务,但是在日志查看器中,每条消息都被视为错误。
根据日志级别,是否有一般建议的记录到 stderr 和 stdout 的方法。即 stderr 的错误和 stdout 的任何其他错误。
我目前正在使用logrus包并且遇到了这个实现。我认为在仍然使用相同包的同时实现这一目标的其他方法是将记录器传递给需要它的每个包或创建一个全局日志对象,这两种方式我都不太热衷。
您可以使用 GoLang 的 Stackdriver 库包:
go get -u cloud.google.com/go/logging
Run Code Online (Sandbox Code Playgroud)
然后你可以使用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")
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处找到Google Cloud 网站上的文档
更新:
这不会将您的应用程序绑定到 Google Cloud Platform。但是,这并不意味着在另一个平台上您不需要更改代码来格式化输出。
使用 StackDriver 库是 Google Cloud 的推荐解决方案。