I need a unique request ID for my logger, so I can track each request in the log file.

So far I got this

REQUEST_ID = Digest::MD5.hexdigest(Time.now.to_f.to_s + $PID.to_s)

The problem is that I don't know where to put this. I tried placing it inside my custom logger file, outside the class. But it must be being cached or something because I'm always getting the same hash.

In production this will be a mess. Notice the newlines after the first line? Now imagine how the logs would look like in a server handling many requests per second. It will be hard to associate a request with a URI

Wow thanks. Is there more documentation about this? What other tags can I add? Also, it's adding ugly spaces as in the logs you posted (see the spaces before 'Rendered'). Do you know if I can access the uuid from the outside to make my own logger?
–
HappyDeveloperFeb 21 '12 at 15:54

@HappyDeveloper: yep, it's a method on a request object. So you can access it in your controllers, logger.debug request.uuid.
–
Sergio TulentsevFeb 21 '12 at 15:57

But I need to access the request id from within my initializer because logs start before the controller. Right? What can I do? I'm still stuck with this
–
HappyDeveloperFeb 21 '12 at 16:47

@HappyDeveloper: if you have a custom logger, you can just pass request.uuid as another parameter to logging call. You don't need to do this in initializer, because, naturally, you don't have request at that point.
–
Sergio TulentsevFeb 21 '12 at 16:51

If I can't put the request ID in the very first line of the request logs, then it's useless. I need it to be written in this line: rails[13273][$REQUEST_ID]: Started GET "/" for 127.0.0.1 at Tue Feb 21 14:00:00 -0300 2012. So far everything works except for the request id part. I need to grab it or generate it somehow.
–
HappyDeveloperFeb 21 '12 at 17:02