登录到stderr和stdout golang Google Cloud Platform

2eafrhcq  于 2023-05-20  发布在  Go
关注(0)|答案(4)|浏览(163)

目前在GCP上运行go服务,但是在日志查看器中,每条消息都被视为错误。
是否有一种通常建议的方法来根据日志级别记录到stderr和stdout。即错误到标准错误和任何其他标准输出。
我目前正在使用logrus包,并遇到了这个实现。我看到的在使用同一个包的情况下实现这一点的其他方法是将日志记录器传递给每个需要它的包,或者创建一个全局日志对象,这两种方法我都不太热衷。
https://github.com/microsoft/fabrikate/pull/252/commits/bd24d62d7c2b851ad6e7b36653eb0a6dc364474b#diff-ed0770fdbf87b0c6d536e33a99a8df9c

nbysray5

nbysray51#

您可以使用Stackdriver库包为GoLang:

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的推荐解决方案。

3j86kqsm

3j86kqsm2#

我们使用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")
}
gkl3eglg

gkl3eglg3#

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

wfauudbj

wfauudbj4#

如果你是从一个运行在GKE pod中的进程中进行日志记录,并且你希望你的日志通过stdout流被摄取,那么只需要使用标准的Google golang日志库,但是将其配置为写入stdout。

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

相关问题