Record X-Request-ID in gunicorn access log

Update configuration file

The format of gunicorn's access log can be set in the configuration file. The configuration key is access_log_format.

The default configuration is:

access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'

We can add %({x-request-id}i)s header to the end. It means to get X-Request-ID from request headers.

access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %({x-request-id}i)s'

Command line argument

If you don't want to use a configuration file, you can add an argument access-logformat to the command line.

Here's an example:

gunicorn app:app --access-logfile /path/to/log --access-logformat '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %({x-request-id}i)s'

Example log

127.0.0.1 - - [16/Jun/2022:18:49:10 +0800] "GET / HTTP/1.1" 200 5 "-" "PostmanRuntime/7.29.0" a304135c-15a1-4712-b01b-7ea1e51e1d16

At the end of the log line, a304135c-15a1-4712-b01b-7ea1e51e1d16 is the X-Request-ID header value.

Posted on 2022-06-16