go - 登录到 stderr 和 stdout golang Google Cloud Platform
问题描述
目前在 GCP 上运行 go 服务,但是在日志查看器中,每条消息都被视为错误。
是否有根据日志级别记录到标准错误和标准输出的一般建议方法。即 stderr 的错误和 stdout 的任何其他错误。
我目前正在使用logrus包并且遇到了这个实现。我看到在仍然使用相同包的同时实现此目的的其他方法是将记录器传递给需要它的每个包或创建一个全局日志对象,这两种方法我都不太喜欢。
解决方案
您可以使用 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")
}
您可以在此处找到Google Cloud 网站上的文档
更新:
或者,您可以尝试一下用于 logrus 的 GCP 格式化程序
这不会将您的应用绑定到 Google Cloud Platform。但是,这并不意味着在另一个平台上您不需要更改代码来格式化输出。
使用 StackDriver 库是 Google Cloud 的推荐解决方案。
推荐阅读
- javascript - 如何使用 javascript/nodejs 首先使用 2 个不匹配的列对 excel 表中的数据进行排序,然后再对匹配的列进行排序?
- mysql - 从下拉列表中获取选定的值并在 router.get Nodejs 中使用它
- python - 确定论文推荐中的 Pagerank 和关键字权重
- postgresql - LockRows 计划节点耗时较长
- aws-amplify - 如何在已配置 codegen 的地方运行 amplify codegen?
- javascript - 乾坤输入时触发重绘
- python - 无法在 Heroku 上的 python 应用程序中调用外部 API
- javascript - 自然对数的定义是什么?- 使用代码查找自然对数的值
- javascript - 我想在客户端使用带有 CDN 的 datebook,但出现错误
- python-3.x - LEETCODE 问题 - 将所有球移动到每个盒子的最小操作数