Skip to content

Instantly share code, notes, and snippets.

@erikcw
Last active August 22, 2023 10:58
Show Gist options
  • Save erikcw/e999e1fb438dbbb91533 to your computer and use it in GitHub Desktop.
Save erikcw/e999e1fb438dbbb91533 to your computer and use it in GitHub Desktop.
Simple nginx lua script to add UUID to each request for end to end request tracking.
# Dependencies
# nginx_lua
# lua uuid module (luarocks install uuid)
http {
# this will be the request id
map $host $request_uuid {
default '';
}
log_format log_with_request_id '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'request_id: $request_uuid';
server {
# your server block here ...
access_log /var/log/nginx.log log_with_request_id;
set_by_lua $request_uuid '
if ngx.var.http_x_request_id == nil then
return uuid()
else
return ngx.var.http_x_request_id
end
';
}
}
@mjpieters
Copy link

mjpieters commented Aug 9, 2023

Looks like it could be implemented just with plain nginx's if and set statements:

Your regex doesn't replace hex digit 13, you shifted digit 13-31 to positions 14-32, dropping off the 32nd hex digit. Probably not a big deal if your random values are properly random.

You can use a single map to do all the work with 4 regexes (one for each group of digit 17 values):

# map $request_id, a 32 (lowercase) hex digit random value, to a valid UUID4 value, formatted in 8h-4h-4h-4h-12h format.
# replaces hex digit 13 with '4', and the upper two bits of hex digit 17 with binary '10'
map $request_id $request_uuid4 {
    # <8h><4h><ignored h><3h><h digit for 0b??00><3h><12h>
    "~^(?<uuid_g1>[0-9a-f]{8})(?<uuid_g2>[0-9a-f]{4})[0-9a-f](?<uuid_g3>[0-9a-f]{3})[048c](?<uuid_g4>[0-9a-f]{3})(?<uuid_g5>[0-9a-f]{12})$" "${uuid_g1}-${uuid_g2}-4${uuid_g3}-8${uuid_g4}-${uuid_g5}";
    # <8h><4h><ignored h><3h><h digit for 0b??01><3h><12h>
    "~^(?<uuid_g1>[0-9a-f]{8})(?<uuid_g2>[0-9a-f]{4})[0-9a-f](?<uuid_g3>[0-9a-f]{3})[159d](?<uuid_g4>[0-9a-f]{3})(?<uuid_g5>[0-9a-f]{12})$" "${uuid_g1}-${uuid_g2}-4${uuid_g3}-9${uuid_g4}-${uuid_g5}";
    # <8h><4h><ignored h><3h><h digit for 0b??10><3h><12h>
    "~^(?<uuid_g1>[0-9a-f]{8})(?<uuid_g2>[0-9a-f]{4})[0-9a-f](?<uuid_g3>[0-9a-f]{3})[26ae](?<uuid_g4>[0-9a-f]{3})(?<uuid_g5>[0-9a-f]{12})$" "${uuid_g1}-${uuid_g2}-4${uuid_g3}-a${uuid_g4}-${uuid_g5}";
    # <8h><4h><ignored h><3h><h digit for 0b??11><3h><12h>
    "~^(?<uuid_g1>[0-9a-f]{8})(?<uuid_g2>[0-9a-f]{4})[0-9a-f](?<uuid_g3>[0-9a-f]{3})[37bf](?<uuid_g4>[0-9a-f]{3})(?<uuid_g5>[0-9a-f]{12})$" "${uuid_g1}-${uuid_g2}-4${uuid_g3}-b${uuid_g4}-${uuid_g5}";
}

# use $request_uuid4 in your log directive, or in a addheader directive to send the value back in responses.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment