在水牛城中整合哨兵和弹性APM

时间:2020-03-29 21:29:01

标签: go sentry buffalo elastic-apm

我正在尝试使用Buffalo将Elastic APM和Sentry集成到我的网站中。有趣的文件如下:

handlers/sentryHandler.go

package handlers

import (
    sentryhttp "github.com/getsentry/sentry-go/http"
    "github.com/gobuffalo/buffalo"
)

func SentryHandler(next buffalo.Handler) buffalo.Handler {
    handler := buffalo.WrapBuffaloHandler(next)
    sentryHandler := sentryhttp.New(sentryhttp.Options{})

    return buffalo.WrapHandler(sentryHandler.Handle(handler))
}

handlers/elasticAPMHandler.go

package handlers

import (
    "fmt"

    "github.com/gobuffalo/buffalo"
    "go.elastic.co/apm/module/apmhttp"
)

func ElasticAPMHandler(next buffalo.Handler) buffalo.Handler {
    fmt.Println("AAA")
    handler := apmhttp.Wrap(buffalo.WrapBuffaloHandler(next))
    return buffalo.WrapHandler(handler)
}

actions/app.go

package actions

import (
    "github.com/gobuffalo/buffalo"
    "github.com/gobuffalo/envy"
    forcessl "github.com/gobuffalo/mw-forcessl"
    paramlogger "github.com/gobuffalo/mw-paramlogger"
    "github.com/unrolled/secure"

    "my_website/handlers"
    "my_website/models"

    "github.com/gobuffalo/buffalo-pop/pop/popmw"
    csrf "github.com/gobuffalo/mw-csrf"
    i18n "github.com/gobuffalo/mw-i18n"
    "github.com/gobuffalo/packr/v2"
)

func App() *buffalo.App {
    if app == nil {
        app = buffalo.New(buffalo.Options{
            Env:         ENV,
            SessionName: "_my_website_session",
        })

        // Automatically redirect to SSL
        app.Use(forceSSL())

        // Catch errors and send them to Sentry.
        app.Use(handlers.SentryHandler)

        // Get tracing information and send it to Elastic.
        app.Use(handlers.ElasticAPMHandler)

        // Other Buffalo middleware stuff goes here...

        // Routing stuff goes here...
    }

    return app
}

我遇到的问题是,如果我在顶部有Sentry / APM处理程序,那么我会收到类似application.html: line 24: "showPagePath": unknown identifier的错误。但是,如果我将其移动到设置路线之前,则会收到未找到事务的错误。因此,我猜测处理程序包装程序正在丢弃buffalo.Context信息。那么,从尝试重新实现包装程序开始,我该怎么做才能将Sentry和Elastic集成到Buffalo助手中?

1 个答案:

答案 0 :(得分:0)

因此,我猜想处理程序包装程序将删除buffalo.Context信息。

是的。问题在于,buffalo.WrapHandlerSource)会丢弃除基础http.Request / http.Response之外的所有上下文:

// WrapHandler wraps a standard http.Handler and transforms it
// into a buffalo.Handler.
func WrapHandler(h http.Handler) Handler {
    return func(c Context) error {
        h.ServeHTTP(c.Response(), c.Request())
        return nil
    }
}

那么,从尝试重新实现包装程序开始,我该怎么做才能将Sentry和Elastic集成到Buffalo助手中?

我可以看到两个选项:

  • 重新实现buffalo.WrapHandler / buffalo.WrapBuffaloHandler以停止丢弃buffalo.Context。这将涉及将buffalo.Context存储在基础http.Request的上下文中,然后在另一侧再次将其拉出,而不是创建一个全新的上下文。
  • 在不使用Wrap*函数的情况下为Sentry和Elastic APM实现Buffalo专用的中间件。

Elastic APM代理中的后一种选项elastic/apm#39中存在一个未解决的问题。