Skip to content

Instantly share code, notes, and snippets.

@pavelpatrin
Last active October 22, 2018 21:32
Show Gist options
  • Save pavelpatrin/702bd624225dd0515542a79a5c2c2a01 to your computer and use it in GitHub Desktop.
Save pavelpatrin/702bd624225dd0515542a79a5c2c2a01 to your computer and use it in GitHub Desktop.
Flamegraph middleware that tracks requests
class FlamegraphMiddleware(object):
def __init__(self):
import os, socket, datetime
arguments = os.getpid(), socket.gethostname()
filename = '/tmp/flamegraph.%s.%s.log' % arguments
self.profiler = self.create_profiler(filename)
print('FlameGraph started: %s' % filename)
def __del__(self):
self.profiler.stop()
self.profiler.join()
print('FlameGraph finished')
def create_profiler(self, filename):
import time
from flamegraph import flamegraph
class ProfileThread(flamegraph.ProfileThread):
u"""
ProfilerThread that supports pausing.
"""
@property
def _keeprunning(self):
while getattr(self, '__paused', False):
time.sleep(0.001)
return self.__keeprunning
@_keeprunning.setter
def _keeprunning(self, value):
self.__keeprunning = value
def watch(self):
self.__paused = True
def sleep(self):
self.__paused = False
flamegraph.ProfileThread = ProfileThread
return flamegraph.start_profile_thread(fd=open(filename, 'w'))
def process_request(self, request):
self.profiler.watch()
def process_exception(self, request, exception):
self.profiler.sleep()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment