Include a Request ID in All Logs
Learn how to add a request ID in all the logs.
We'll cover the following...
Many hosting providers or web servers generate a unique value for each request and set that value in the HTTP header X-Request-Id
. If that happens, Rails can provide us with that value. Each controller in a Rails app exposes the request
method, which provides access to the HTTP headers. Even better, we can call the method request_id
on request to get the value of the X-Request-Id
header or, if there is no value, have Rails generate a unique request ID for us.
If we include this value in all our log statements, we can use the request ID to correlate all activity around a given request. For example, if we see that widget 1234
was saved as part of request ID 1caebeaf
, we can search the log for that request ID and see all log statements from all code called as part of ...