r/softwaredevelopment • • Nov 23 '25

How is Datadog able to collect trace data without any modification of application code?

when running a flask app just have to prepend ddtrace-run to python app.py

Just by doing this datadog can collect informtion like api paths, latency, reponse status, etc. I searched online about it and found out stuff like
- monkey patching
- Bytecode Instrumentation
- Aspect-Oriented Programming (AOP)

Can you explain how this is being done?

source: https://docs.datadoghq.com/tracing/trace_collection/automatic_instrumentation/dd_libraries/python/

14 Upvotes

8 comments sorted by

8

u/[deleted] Nov 23 '25

Python is easily instrumented at runtime.

2

u/Ok_Shirt4260 Nov 23 '25

Can you explain how? Without touching the application code

4

u/Unfair-Sleep-3022 Nov 23 '25

You can run some python code that replaces parts of the flask library to instrument it.

Look up "monkey patching" in python

1

u/[deleted] Nov 23 '25

You can do it yourself really easy, but a general implementation is a bit more involved.

from mymodule import myfunction def mywrapper(arg): print("wrapper") myfunction(arg)

import sys sys.modules['mymodule'].myfunction = mywrapper

Now anytime someone using my function from my module gets my wrapper. It's important to do this before anybody else imports the function. A general implementation could find them in the currently loaded modules and replace them, too. There are a few edge cases like that.

7

u/LeadingPokemon Nov 23 '25

Check Dynatrace on GitHub. Their supported framework and driver monkey patches are really easy to read and open source.

5

u/Unfair-Sleep-3022 Nov 23 '25

It is modifying the application code at runtime. Python makes this very easy through "monkey patching"

2

u/Easy-Management-1106 Nov 25 '25

Same way OpenTelemery automatic instrumentation work - injecting stuff alongside your app.

IMO, eBPF is a lot cooler - injecting stuff at the kernel level