How to write a custom tracer/profiler?

Gabriel Genellina gagsl-py2 at
Tue Jul 15 07:51:39 CEST 2008

En Mon, 14 Jul 2008 23:48:20 -0300, AK at SYD <anthony.hw.kong at>  

> The main logic will issue a number of calls to the DS in order to get
> the data it needs and then carry out some calculations.
> I want to have a non-intrusive way to find out all the DS data
> requested by the main logic.
> One thing to note, the DS is a big, messy bit of code. So putting
> logger everywhere within DS and main logic is not a reliably,
> satisfactory solution.
> I have thought about using somehting like aspect. But seems to me
> there is no mature, widely-used aspect lib out there.
> Another idea is: let's roll a custom tracer/profiler. Whenever any
> method/attributes in the DS package are called, the return values will
> be logged.
> I have taken a quick look at in python 2.4, It seems sys
> module will pass a frames to the profile class. Can I access the
> return value of a function via these frame objects?

You don't have to use a profiler; just replace the original DS functions  
that you're interested in monitoring, with a "wrapped" version that logs  
its parameters and then calls the original code. A skeleton example  
(suppose is one function you want to monitor):

import DS
original_open =

def wrapped_open(*args, **kw):
     trace("open", *args, **kw)
     return original_open(*args, **kw) = wrapped_open

This approach has some problems (it does not preserve the original  
function signature, by example). You may overcome this (and other  
problems) using the decorator module from M. Simionato; see  

Gabriel Genellina

More information about the Python-list mailing list