How to implement logging for an imported module?

Dieter Maurer dieter at handshake.de
Sun Mar 7 13:00:00 EST 2021


Robert Latest wrote at 2021-3-7 10:21 GMT:
>I'm trying to add logging to a module that gets imported by another module. But
>I only get it to work right if the imported module knows the name of the
>importing module. The example given in the "Logging Cookbook" also rely on this
>fact.

I have used so called "monkey patching" to achieve something like this
(in fact "function call tracing").
"monkey patching" means code modification at runtime.

Suppose your application implements a logging decorator `log`.
Then on import, you can replace methods (easiest) or functions
with decorated variants either directly in the imported module/class
or for use by the importer.


More information about the Python-list mailing list