MYK
MYK

Reputation: 2977

How to implement an implicit logger in Python?

I want to add some helpful logging to a Python codebase.

I'm looking to add logging roughly of the form:

[2022-01-06 10:00:01] function foo called with args x=1, y=22, z=3
[2022-01-06 10:00:05] function foo returned 1416
[2022-01-06 10:00:13] function bar called with args w=1416
[2022-01-06 10:00:16] function bar returned None

I could do this by wrapping all functions in the codebase with a decorator, but is there a better way? At least to indicate the timestamp and order in which functions are being called.

I could implement the decorator:

def logthis(func):
    def inner(*args, **kwargs):
        logger.info(f'Calling {func.__name__} with args={args} and kwargs={kwargs}')
        ans = func(*args, **kwargs)
        logger.info(f'Function {func.__name__} returned {ans}')
        return ans
    return inner

@logthis
def foo(x, y, z):
   return x+y+z

@logthis
def bar(w):
   return None

This works reasonably well; provided I'm happy to add it across my whole codebase.

Upvotes: 0

Views: 180

Answers (1)

ZXYNINE
ZXYNINE

Reputation: 732

You can use the inspect module. I typically use it to implement a "Get the filepath of the function that called this function" method I use for various reasons. inspect.stack() (see this) may be what you are looking for as you can go up the list of callers and create info about it.

From there I think the only problem you'd have is how to log the time. Another idea is two create a wrapper for entire classes or a function that you pass __locals__() to that gets all functions and applies a decorator to them. That method is going somewhat into meta programming since you'd have to reconstruct the class objects /update/wrap all of their functions like you have and whatnot, but it could save you a fair amount of tedious work.

Also see the traceback module.

Upvotes: 1

Related Questions