0

I'm implementing a logger of method calls from derivate classes as suggested by this answer:

class Logger:
    def _decorator(self, f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            print(f.__name__, args, kwargs) # I'll replace this with my logging logic
            return f(*args, **kwargs)

        return wrapper

    def __getattribute__(self, item):
        value = object.__getattribute__(self, item)
        if callable(value):
            decorator = object.__getattribute__(self, '_decorator')
            return decorator(value)
        return value


class A(Logger):
    def method(self, a, b):
        print(a)

    def another_method(self, c):
        print(c)

    @staticmethod
    def static_method(d):
        print(d)

I'm worried that my logging logic may disrupt the method calls from the derivate classes. In particular, because the logging may involve some call to a database, I'm worried that this can cause some unnecessary delay to the logged method. And I surely don't want any errors during the logging spilling over the methods.

Is there a way to make the logging logic asynchronous to the method call here? It doesn't bother me to use the async toolbox from Python in Logger, but I'd like to keep A and any program that will instantiate it totally unaware of it. In other words, A and the client code should not need to worry about things like asyncio, async and await.

sourcream
  • 210
  • 1
  • 11

1 Answers1

0

One way to implement this is to create a task when you instantiate your logger which constantly queries a queue for log events to send to the database. This way your main thread that calls your logging function will add to this queue (very fast operation) and your new task will have a while True: loop that queries the queue, sees there are available logging events, and sends them to the database.

rene
  • 146
  • 5