aboutsummaryrefslogtreecommitdiff
path: root/rhodecode/lib/profiler.py
blob: f2e54f065c8a2490022c03896ce0198c4d3223c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from __future__ import with_statement

import gc
import objgraph
import cProfile
import pstats
import cgi
import pprint
import threading

from StringIO import StringIO


class ProfilingMiddleware(object):
    def __init__(self, app):
        self.lock = threading.Lock()
        self.app = app

    def __call__(self, environ, start_response):
        with self.lock:
            profiler = cProfile.Profile()

            def run_app(*a, **kw):
                self.response = self.app(environ, start_response)

            profiler.runcall(run_app, environ, start_response)

            profiler.snapshot_stats()

            stats = pstats.Stats(profiler)
            stats.sort_stats('calls') #cummulative

            # Redirect output
            out = StringIO()
            stats.stream = out

            stats.print_stats()

            resp = ''.join(self.response)

            # Lets at least only put this on html-like responses.
            if resp.strip().startswith('<'):
                ## The profiling info is just appended to the response.
                ##  Browsers don't mind this.
                resp += ('<pre style="text-align:left; '
                         'border-top: 4px dashed red; padding: 1em;">')
                resp += cgi.escape(out.getvalue(), True)

                ct = objgraph.show_most_common_types()
                print ct

                resp += ct if ct else '---'

                output = StringIO()
                pprint.pprint(environ, output, depth=3)

                resp += cgi.escape(output.getvalue(), True)
                resp += '</pre>'

            return resp