Is there a way to log a per request unique id for nginx?

There appear to be a couple of third party modules for this

  • https://github.com/newobj/nginx-x-rid-header
  • https://github.com/hhru/nginx_requestid

However if possible I don't want to rebuild nginx, which I believe, is a requirement to use both of these modules. My initial try was to use $msec with $pid however that didn't work out (I had a process serve two requests at the same millisecond). I've read about $connection and it seems like that would work in conjunction with $msec. Will this work or is there a better way without using third party modules?


Update for nginx version v1.11 (May 2016):

http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_id

You can use $request_id:

unique request identifier generated from 16 random bytes, in hexadecimal (1.11.0)


You can use nginx-extras and use embedded Perl or Lua.

$ sudo apt-get install libossp-uuid-perl

In your nginx configuration:

perl_require "Data/UUID.pm";
perl_set $request_uuid 'sub {

    my $ug = new Data::UUID;
   return $ug->create_str();
}';

And then for a given location:

proxy_set_header Request-Id $request_uuid

We're using this in production and are very happy with the better tracing that we have across our backend services.