Created
December 12, 2017 12:23
-
-
Save michaeltcoelho/c8bc65e5c3dce0f85312349353bf155a to your computer and use it in GitHub Desktop.
Gunicorn Python cProfile for Python 3.6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cProfile | |
import pstats | |
from io import StringIO | |
import logging | |
import os | |
import time | |
PROFILE_LIMIT = int(os.environ.get("PROFILE_LIMIT", 30)) | |
PROFILER = bool(int(os.environ.get("PROFILER", 1))) | |
print(""" | |
# ** USAGE: | |
$ PROFILE_LIMIT=100 gunicorn -c ./wsgi_profiler_conf.py wsgi | |
# ** TIME MEASUREMENTS ONLY: | |
$ PROFILER=0 gunicorn -c ./wsgi_profiler_conf.py wsgi | |
""") | |
def profiler_enable(worker, req): | |
worker.profile = cProfile.Profile() | |
worker.profile.enable() | |
worker.log.info(f"PROFILING {worker.pid}: {req.uri}") | |
def profiler_summary(worker, req): | |
s = StringIO() | |
worker.profile.disable() | |
ps = pstats.Stats(worker.profile, stream=s).sort_stats('time', 'cumulative') | |
ps.print_stats(PROFILE_LIMIT) | |
logging.error(f"\n[{worker.pid}] [INFO] [{req.method}] URI {req.uri}") | |
logging.error(f"[{worker.pid}] [INFO] {s.getvalue()}") | |
def pre_request(worker, req): | |
worker.start_time = time.time() | |
if PROFILER is True: | |
profiler_enable(worker, req) | |
def post_request(worker, req, *args): | |
total_time = time.time() - worker.start_time | |
logging.error(f"\n[{worker.pid}] [INFO] [{req.method}] Load Time: {total_time}s\n") | |
if PROFILER is True: | |
profiler_summary(worker, req) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment