Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a trace id in nginx load balancer

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.

like image 676
danny Avatar asked Jul 19 '13 14:07

danny


People also ask

What is nginx tracing?

The NGINX OpenTracing module enables tracing of NGINX Plus requests and responses, and provides access to NGINX Plus variables using OpenTracing tags. Different tracers can also be used with this module. For more details about the NGINX OpenTracing module, visit the NGINX OpenTracing module repo on GitHub.

Can nginx work as a load balancer?

It is possible to use nginx as a very efficient HTTP load balancer to distribute traffic to several application servers and to improve performance, scalability and reliability of web applications with nginx.

What is Proxy_set_header nginx?

To adjust or set headers for proxied connections, use the proxy_set_header directive, followed by the header value. You can find a list of all available Request Headers and their allowed values here . If you want to prevent a header from being passed to the proxied server, set it to an empty string "" .


2 Answers

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

like image 149
isapir Avatar answered Sep 21 '22 15:09

isapir


In most cases you don't need a custom module, you can simply set a header with a combination of embedded variables of http_core_module which is (most probably) unique. Example:

  location / {       proxy_pass http://upstream;       proxy_set_header X-Request-Id $pid-$msec-$remote_addr-$request_length;   } 

This would yield a request id like "31725-1406109429.299-127.0.0.1-1227" and should be "unique enough" to serve as a trace id.

like image 42
sbange Avatar answered Sep 22 '22 15:09

sbange