Search code examples
pythonpython-decoratorspython-logging

Built-in decorator to log method calls


The following code (or custom solutions from Better way to log method calls in Python? or solutions with inspect) works to log method calls:

import logging, sys

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger()

def log(func):
    def logged(*args, **kwargs):
        logger.info(f"{func.__name__} starting with {args=} {kwargs=}...")
        result = func(*args, **kwargs)
        logger.info(f"{func.__name__} finished.")
        return result
    return logged

class A:
    @log
    def foo(self, x, y):
        pass

    @log
    def bar(self, x, y):
        1/0

a = A()
a.foo(2, y=3)
a.bar(2, y=3)

Output:

INFO:root:foo starting with args=(<__main__.A object at 0x0000000002784EE0>, 2) kwargs={'y': 3}...
INFO:root:foo finished.
INFO:root:bar starting with args=(<__main__.A object at 0x0000000002784EE0>, 2) kwargs={'y': 3}...
...

Is there a built-in solution in current Python versions (either in logging or in another module)?


Solution

  • There is no @log-like decorator in Python 3.12.1's logging module

    I looked through the source code and test code for logging and didn't see any functionality that allowed any type of declarative way of identifying methods to log nor did I find any tests that tested any type of decorator in the logging module tests.