简体   繁体   English

如何在 go.uber.org/zap/zapcore logger 中使用 Sentry

[英]How to use Sentry with go.uber.org/zap/zapcore logger

I am using go.uber.org/zap/zapcore for logging in my Go app.我正在使用go.uber.org/zap/zapcore登录我的 Go 应用程序。

package logger

import (
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
    "log"
)

var l *zap.Logger

func Get() *zap.Logger {
    return l
}

func Init() {
    conf := zap.NewProductionConfig()

    logger, err := conf.Build()
    if err != nil {
        log.Fatal("Init logger failed", err)
    }
    l = logger
}

I also have Sentry project and use github.com/getsentry/raven-go .我也有哨兵项目并使用github.com/getsentry/raven-go

I want to send logs at error level and above to Sentry.我想将error级别及更高级别的日志发送到 Sentry。

For example when logging at info level with logger.Info() I want to just log them as usual, but in case of error or fatal logs I need send these messages to Sentry.例如,当使用logger.Info()info级别登录时,我只想像往常一样记录它们,但是如果出现errorfatal日志,我需要将这些消息发送给 Sentry。 How can I achieve that?我怎样才能做到这一点?

The answer is you should use zap wrapper for adding hooks then you have to use the function of logger which is called WithOptions答案是你应该使用 zap 包装器来添加钩子,然后你必须使用名为 WithOptions 的记录器功能

sentryOptions := zap.WrapCore(func(core zapcore.Core) zapcore.Core {
    return zapcore.RegisterHooks(core, func(entry zapcore.Entry) error {
        // your logic here
    })
})

logger.WithOptions(sentryOptions)

The following will capture the message and send it to the sentry when an error level is detected, with customized error line number and message.下面将捕获消息并在检测到错误级别时将其发送给哨兵,并带有自定义的错误行号和消息。

err := sentry.Init(sentry.ClientOptions{Dsn: "http://~~~~~"})
if err != nil {
    log.fatal("Sentry Error Setup ::", err.Error())
}

logger, _ := zap.NewDevelopment(zap.Hooks(func(entry zapcore.Entry) error {
    if entry.Level == zapcore.ErrorLevel {
        defer sentry.Flush(2 * time.Second)
        sentry.CaptureMessage(fmt.Sprintf("%s, Line No: %d :: %s", entry.Caller.File, entry.Caller.Line, entry.Message))
    }
    return nil
}))

sugar := logger.Sugar()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM