Include a Request ID in All Logs

Learn how to add a request ID in all the logs.

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 include this value when we call Rails.logger.info. The default logging from Rails’ controllers does include this value. However, lograge removes it for some reason. Let’s add that back and then discuss how to include the request ID in log messages that aren’t written from our controllers.

First, we’ll modify ApplicationController to include the request ID in a hash that lograge will have access to. We can do that by overriding the append_info_to_payload method, which Rails calls to allow inserting custom information into a special object used for each request.

Get hands-on with 1200+ tech skills courses.