Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to SetUserContext in a request? #83

Open
montanaflynn opened this issue Mar 29, 2019 · 2 comments
Open

How to SetUserContext in a request? #83

montanaflynn opened this issue Mar 29, 2019 · 2 comments

Comments

@montanaflynn
Copy link

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
Copy link
Author

@evalphobia any ideas here?

@evalphobia
Copy link
Owner

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants