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.
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.
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.
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 "" .
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With