Autologging icon indicating copy to clipboard operation
Autologging copied to clipboard

Log whole modules / functions outsides classes / whole application

Open valentijnscholten opened this issue 3 years ago • 4 comments

Hi,

I am dealing with a fairly large somewhat older python django project which mainly consists of python files with lots of functions without any Classes.

import os

def function1():
      do_stuff()

Is there anyway I can use autologging to log all these function calls? I believe from the docs the @logged and @traced only work on class or method level?

valentijnscholten avatar Oct 01 '20 06:10 valentijnscholten

Hi @valentijnscholten - sorry it took a whiel to respond.

The @traced decorator can be applied to functions at module level. Here are two examples:

# in module "my.app"

_module_logger = logging.getLogger("named.channel")

@traced
def function1(...):
    ...

@traced(_module_logger):
def function2(...):
    ...

What you see in the logs depends on whether or not you pass an explicit logger (as with function2) or not (as with function1).

In the case of function1, the log channel will be the fully-qualified dotted-name of the module in which the function is defined (here that's "my.app").

In the case of function2, the log channel will be taken from the passed-in logger (here that would be "named.channel").

You are correct that the @logger decorator is intended for classes. The responsibility of @logged is simply to assign a logger as a member of the decorated class; doing this makes little sense for module-level functions as they can (should?) just use a module-level logger as shown above.

Let me know if that answers your question.

Also, here's the documentation specifically for @traced where you can see additional examples for both classes and functions: https://autologging.readthedocs.io/en/latest/examples-traced.html

mzipay avatar Jan 08 '21 21:01 mzipay

Thanks. What I meant is, is there anyway to use auto logging for all functions in a module (or app) all at once, without having to decorate each function.

valentijnscholten avatar Jan 08 '21 21:01 valentijnscholten

Ah, no there isn't any kind of app/module scanning implemented in the library, so yes you either have to decorate the functions or, if they are in 3rd party modules, you'd need to resort to doing something like

import some.module
some.module.func = traced(some.module.func)

mzipay avatar Jan 08 '21 21:01 mzipay

If you'd like, feel free to submit a feature request for module scanning.

mzipay avatar Jan 08 '21 21:01 mzipay