Setting a trace id in nginx load balancer

danny picture danny · Jul 19, 2013 · Viewed 23.2k times · Source

I'm using nginx as a load balancer in front of several upstream app servers and I want to set a trace id to use to correlate requests with the app server logs. What's the best way to do that in Nginx, is there a good 3rd party module for this?

Otherwise a pretty simple way would be to base it off of timestamp (possibly plus a random number if that's not precise enough) and set it as an extra header on the request, but the only set_header command I see in the docs is for setting a response header.

Answer

isapir picture isapir · Jul 19, 2016

nginx 1.11.0 added the new variable $request_id which is a unique identifier, so you can do something like:

   location / {
      proxy_pass http://upstream;
      proxy_set_header X-Request-Id $request_id;
   }

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