Include a Request ID in All Logs
Explore how to integrate unique request IDs into every log entry in Rails to improve traceability of actions during a request. Learn techniques for adding request IDs both in controller logs and deeper application layers using thread-local storage and custom log wrappers.
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 saving widget 1234. This is extremely powerful!
The problem is that Rails doesn’t automatically ...