Record elapsed time of every request (request time) 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 %(L)s header to the end. It means request time in decimal seconds.

access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(L)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" %(L)s'

Example log

127.0.0.1 - - [16/Jun/2022:18:50:35 +0800] "GET / HTTP/1.1" 200 5 "-" "PostmanRuntime/7.29.0" 3.004339

At the end of the log line, 3.004339 is the request time. It's about 3 seconds.

Posted on 2022-06-16