Correlating Rails Log That Belongs to the Same Request

By default, Rails application logs look like the snippet below. This belongs to only one application request, which is the GET /users request:

While the logs seem to be ordered and all the lines that belong to the request are tied to each other, this is not the case when the application is running on production environments with multi-thread/multi-process web servers such puma or unicorn . In that case, multiple processes/threads will be writing logs and there is no guarantee that each request log will appear tied together. Actually, the logs from different requests will be overlapping each other and the logs on a production system could look like the snippet below:

From the snippet above, it is very hard (if not impossible ) to tell which log line belongs to which request. Luckily, Rails can be configured easily to correlate the log lines that belong to the same requests using ActionDispatch:RequestId middleware. This middleware generates a random unique request-id or uses the request-id passed in the request headers. We can use this id to tag the Rails logs to correlate the Rails log lines. This task can be done by performing the following changes on the Rails application’s source code :

Adding the following line to either config/environments/${env}.rb to apply the change to a specific environment (such as production ) or to the config/application.rb to apply the change to all supported environments:

config.log_tags = [ :uuid ]

After implementing the change above, Rails logs will look like the log snippet below. All the lines that belong to the same request will be tagged by the same request-id value.

That was an easy change, but what if we would like to correlate logs that belong to different applications? Can we use the same request-id?