sirupsen / logrus

Structured, pluggable logging for Go.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to log concurrent http requests with unique request_id

skyrain opened this issue · comments

Currently, I am trying to add request_id information inside every http request log.

The key issue is that we can have multiple requests reaching server concurrently. We do not want the request_id field to be overwritten by different concurrent requests. So here leaves us two options:

Option 1:
Create a new logrus per http request handling, e.g.

Logger{
		logrus.New().WithField("component", componentName),
}

Then use WithField to set requestID information in this logrus.

Option 2:
Use a global logrus, and embed the requestID information somehow manually via logrus.Infof.e.g.

logrus.Infof("This is a log with requestID:" + xxxx)

Option 1 is easier in implement, we just need to create new logrus entry per request, and it will not have any race condition against concurrent requests, but I am concerned that this option might consumes unnecessary cpu/memory as every request will asks me to create a new logrus.

Option 2 is less cpu/memory consuming, as only one global logrus instance needed, but it asks me to write too much template code(might be eliminated since I can always write a logrus wrapper). Also, this option is not using WithField which logrus advocates, and the logging format is plain string instead of formatted json.

Which option does logrus advocate in above situation? Any other better options?

Hello. I think what you can still use your global logger, but at the beggining of your handler, you should use GlobalLogger.NewEntry(), and subsequent use in your handler should use that entry instead of your global logger