登录
首页 >  Golang >  Go问答

选择适合在 GAE 中为 Go 使用的日志库

来源:stackoverflow

时间:2024-03-15 12:21:26 344浏览 收藏

golang学习网今天将给大家带来《选择适合在 GAE 中为 Go 使用的日志库》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我找到了两种gae的go库:

  1. “google.golang.org/appengine/log”
  2. “cloud.google.com/go/logging”

我应该使用哪一个? 顺便说一下,我在我的应用程序中使用了两个日志库。 在本地开发模式下,我可以看到这样的日志。

2019/01/08 06:57:34 info: search keyword="test" idonly=bool
2019/01/08 06:57:34 info: search:"test"

但是当我部署到生产 gae 时,我看不到任何日志。

无论使用stackdriver还是

resource.type="gae_app" resource.labels.module_id="default"

或 gcloud 命令

44712​​8369417

解决方案


如果您希望日志显示在 stackdriver logging 中,正确的方法是使用 "google.golang.org/appengine/log" package

但是,根据 documentation on the Go1.11 runtime,建议使用 not to use the App Engine specific API's and use the Google Cloud client library

关于日志记录,这意味着建议使用 "log" package,而不是使用“google.golang.org/appengine/log”。一个例子:

app.yaml

runtime: go111

hello.go

package main

import (
        "fmt"
        "log"
        "net/http"
        "os"
)

func main() {
        http.handlefunc("/", indexhandler)

        port := os.getenv("port")
        if port == "" {
                port = "8080"
        }

        log.fatal(http.listenandserve(fmt.sprintf(":%s", port), nil))
}

func indexhandler(w http.responsewriter, r *http.request) {
        //create the log and write it
        log.printf("hello world!")
        fmt.fprint(w, "log written in stackdriver!")
}

此日志将显示在 stackdriver logging 中:

resource.type="gae_app"
resource.labels.module_id="default"
logname="projects//logs/stderr"

或者通过在日志过滤器下拉列表中选择 stderr

不过,如果您愿意,您仍然可以使用“google.golang.org/appengine/log”软件包,但您还必须添加“google.golang.org/appengine”软件包,并添加appengine.main() main() 函数中的入口点。

您也可以采用 structured logging 路线,在该路线中您不依赖于上述客户端库。

// entry defines a log entry.
type entry struct {
    message  string `json:"message"`
    severity string `json:"severity,omitempty"`
    trace    string `json:"logging.googleapis.com/trace,omitempty"`

    // cloud log viewer allows filtering and display of this as `jsonpayload.component`.
    component string `json:"component,omitempty"`
}

// string renders an entry structure to the json format expected by cloud logging.
func (e entry) string() string {
    if e.severity == "" {
        e.severity = "info"
    }
    out, err := json.marshal(e)
    if err != nil {
        log.printf("json.marshal: %v", err)
    }
    return string(out)
}

然后使用内置的 log 包进行日志记录:

log.Println(Entry{
        Severity:  "NOTICE",
        Message:   "This is the default display field.",
        Component: "arbitrary-property",
        Trace:     trace,
    })

这是一个完整的示例:https://github.com/GoogleCloudPlatform/golang-samples/blob/master/run/logging-manual/main.go

以上就是《选择适合在 GAE 中为 Go 使用的日志库》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>