首页 > 解决方案 > 登录到 stderr 和 stdout golang Google Cloud Platform

问题描述

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

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

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

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

标签: gologginggoogle-cloud-platform

解决方案


您可以使用 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 的推荐解决方案。


推荐阅读