记录到 stderr 和 stdout golang Google Cloud Platform
时间:2024-04-06
浏览:322
作者:佚名
Golang不知道大家是否熟悉?今天我将给大家介绍《记录到 stderr 和 stdout golang Google Cloud Platform》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!
当前在 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
这不会将您的应用绑定到 google cloud platform。但是,这并不意味着在另一个平台上您不需要更改代码来格式化输出。
使用 stackdriver 库是 google cloud 的推荐解决方案。
到这里,我们也就讲完了《记录到 stderr 和 stdout golang Google Cloud Platform》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
