Search code examples
newrelic

Newrelic for python to trace all of functions


I have python newrelic agent for my python service. I configured everything using the newrelic.ini file. Now I want to see a trace for all the functions that run on my service.

I see the option transaction_tracer.function_trace there but from the explanation in the file it seems like I have to specify each function individuality, which is too hard to maintain. is there a way to set it or other config so that all of the functions will be traced?

How its looking in my python service: enter image description here Part of how its looking in the java service and my goal for the python service: enter image description here


Solution

  • I ended up adding a metaclass to all of my classes that uses the decorator trace_function on all of the class functions.

    from types import FunctionType
    
    import newrelic.agent
    
    
    class TraceClassFunctionsMetaclass(type):
        def __new__(cls, class_name: str, bases: tuple, class_attributes: dict):
            for attr_name, attr_value in class_attributes.items():
                if isinstance(attr_value, FunctionType) and attr_name != '__init__':
                    class_attributes[attr_name] = newrelic.agent.FunctionTraceWrapper(attr_value)
            return super(TraceClassFunctionsMetaclass, cls).__new__(cls, class_name, bases, class_attributes)
    

    Usage:

    class ExampleClass(metaclass=TraceClassFunctionsMetaclass):
        pass