<s> """<STR_LIT>""" <EOL> import cProfile <EOL> import logging <EOL> import os . path <EOL> import socket <EOL> import simplejson <EOL> import thread <EOL> import time <EOL> from perftools . middleware import Base <EOL> class RemoteProfilingMiddleware ( Base ) : <EOL> logger = logging . getLogger ( __name__ ) <EOL> def __init__ ( self , application , outpath , threshold = <NUM_LIT:0.5> , ** kwargs ) : <EOL> self . application = application <EOL> self . outpath = outpath <EOL> self . threshold = threshold <EOL> self . hostname = socket . gethostname ( ) <EOL> super ( RemoteProfilingMiddleware , self ) . __init__ ( application , ** kwargs ) <EOL> def __call__ ( self , environ , start_response ) : <EOL> self . reqnum += <NUM_LIT:1> <EOL> if not self . should_run ( environ ) : <EOL> return self . application ( environ , start_response ) <EOL> profile = cProfile . Profile ( ) <EOL> start = time . time ( ) <EOL> try : <EOL> return list ( profile . runcall ( self . application , environ , start_response ) ) <EOL> finally : <EOL> stop = time . time ( ) <EOL> try : <EOL> if ( stop - start ) > self . threshold : <EOL> self . report_result ( profile , environ , start , stop , self . outpath ) <EOL> except Exception , e : <EOL> self . logger . exception ( e ) <EOL> def report_result ( self , profile , environ , start , stop , outpath ) : <EOL> thread_ident = thread . get_ident ( ) <EOL> ts_parts = map ( lambda x : str ( int ( x ) ) , divmod ( start , <NUM_LIT> ) ) <EOL> outpath = os . path . join ( self . outpath , ts_parts [ <NUM_LIT:0> ] , ts_parts [ <NUM_LIT:1> ] ) <EOL> outfile_base = '<STR_LIT>' % ( self . reqnum , thread_ident ) <EOL> if not os . path . exists ( outpath ) : <EOL> os . makedirs ( outpath ) <EOL> profile . dump_stats ( os . path . join ( outpath , outfile_base + '<STR_LIT>' ) ) <EOL> with open ( os . path . join ( outpath , outfile_base + '<STR_LIT>' ) , '<STR_LIT:w>' ) as fp : <EOL> fp . write ( simplejson . dumps ( { <EOL> '<STR_LIT>' : dict ( ( k , v ) for k , v in environ . iteritems ( ) if isinstance ( v , basestring ) ) , <EOL> '<STR_LIT>' : start , <EOL> '<STR_LIT>' : stop , <EOL> '<STR_LIT>' : self . reqnum , <EOL> '<STR_LIT>' : thread_ident , <EOL> '<STR_LIT>' : self . hostname , <EOL> } , indent = <NUM_LIT:2> ) ) </s>
