Logging to stderr and 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")
}

在这里,您可以在 Google Cloud 网站上找到文档

更新:


或者,您可以尝试一下 logrus 的 GCP 格式化程序

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

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

我们将 https://github.com/rs/zerolog 与 Init(( 方法中调用的以下方法一起使用,以在全局级别设置日志记录选项:

package main
import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"os"
)
// initializeLogging sets up the logging configuration for the service.
// Invoke this method in your Init() method.
func initializeLogging() {
// Set logging options for production development
if os.Getenv("ENV") != "DEV" {
// change the level field name to ensure these are parsed correctly in Stackdriver
zerolog.LevelFieldName = "severity"
// UNIX Time is faster and smaller than most timestamps
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
} else {
// Set logging options for local development
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}

// Example log
log.Info().Msg("This is how you log at Info level")
}

我推荐 https://github.com/apsystole/log。您可以将loglogrus导入交换为它。它是一个小型的零依赖模块,因此比 logrus 轻得多。

如果您从 GKE Pod 中运行的进程进行日志记录,并且希望通过标准输出流摄取日志,则只需使用标准的 Google golang 日志记录库,但将其配置为写入标准输出。

client, err := logging.NewClient(context.Background(), "projects/"+project)
if err != nil {
return nil, err
}
log := client.Logger(logName, logging.RedirectAsJSON(nil))
return &Logger{
client: client,
log:    log,
}, nil

最新更新