How to hook to the instrumentation layer?


I want to research a bit about how can i attach a hook in Python to the instrumentation layer. I want this for Flask mainly. Let me explain a bit more in deep:

Imagine i have a a very dumb Flask application, it exposes an endpoint via POST, that receives a number and returns the square.

What i want to do is develop a piece of code (not part of the actual application) that can see the request that is sent to the endpoint, which method is being called, which part of the code is being executed, etc…

I dont want to dinamically modify anything, i just want to monitor and listen which parts of the code are being executed. It is similar to what IAST agents do, but not so sofisticated

Any help on this? Where can i read documentation about how to do it and any simple example?


Hi Javi,

it’s not quite clear to me what you mean by “instrumentation layer”, but what you’re describing sounds a bit like a profiler, so have a look at how the profile module does things (it appears to use a function called sys.setprofile).

A simpler approach, if you just want to know when particular functions are called, would be to just replace them.

import functools
def wrap_function(orig_fn):
    def wrapper_fn(*args, **kwargs):
        # Log the call, or something
        return orig_fn(*args, **kwargs)
    return wrapper_fn

flask.some_internal_function = wrap_function(flask.some_internal_function)

Hi. Thanks for the answer. Not exactly this. It is tracking like the server has been called with this data in the http request, then, it called, method do_something(param) on line 40 from the file, and it returned “aaaa”.

I have managed to do something with sys.settrace() but I still can’t see the parameters sent to the functions or the data returned by the function.

Also, can’t see what is the http request sent to the flask server, but probably settrace will not provide that info.

Hope it helps to understand what I want