evalphobia / logrus_sentry

sentry hook for logrus
MIT License
194 stars 78 forks source link

How to SetUserContext in a request? #83

Open montanaflynn opened 5 years ago

montanaflynn commented 5 years ago

I'm using the hook but don't know how to add the special user keys inside a request. I found https://godoc.org/github.com/evalphobia/logrus_sentry#SentryHook.SetUserContext but I create the hook and add it to my logger before the API starts. I want to change the user context on a per request basis.

montanaflynn commented 5 years ago

@evalphobia any ideas here?

evalphobia commented 5 years ago

@montanaflynn Sorry for my late reply. SetUserContext sets user data into sentry client directly.

If you want to use this method for each request from users and set different users data, you need to use/create different logrus/sentry hook client variables instead of shared global variable. (I don't think it's a good idea...)

I recommend to set user data into user key in a logrus.Fields .

import (
    "net/http"
    "strconv"

    "github.com/evalphobia/logrus_sentry"
    "github.com/getsentry/raven-go"
    "github.com/sirupsen/logrus"
)

var logger *logrus.Logger

var levels = []logrus.Level{
    logrus.InfoLevel,
    logrus.ErrorLevel,
}

// initialize logger and hook.
func Init(dsn string) error {
    hook, err := logrus_sentry.NewSentryHook(dsn, levels)
    if err != nil {
        return err
    }

    logger = logrus.New()
    logger.AddHook(hook)
    return nil
}

// save info level log.
func LogInfo(data LogData) {
    f := logrus.Fields{}

    if data.UserID > 0 {
        f["user"] = raven.User{
            ID:       strconv.Itoa(data.UserID),
            Username: data.UserName,
            Email:    data.UserEmail,
            IP:       data.UserIP,
        }
    }
    if data.Request != nil {
        f["http_request"] = data.Request // or *raven.Http
    }
    if len(data.Tags) != 0 {
        f["tags"] = data.Tags
    }
    if data.Err != nil {
        f["error"] = data.Err
    }

    f["server_name"] = "my-webserver-01"

    logger.WithFields(f).Info(data.LogTitle)
}

type LogData struct {
    LogTitle string
    Err      error

    Request   *http.Request
    Tags      raven.Tags
    UserID    int
    UserName  string
    UserEmail string
    UserIP    string
}

here's what's happen in this line. https://github.com/evalphobia/logrus_sentry/blob/master/data_field.go#L111