Vyacheslav
Vyacheslav

Reputation: 77

Python decorator that uses an instance of the class Logger for all the methods it decorates

Can you show an example of how to create a function decorator that wrap it with logging, but uses the same logger instance?

For example, take a look on logging_instance. It will be wrong to create it every time the decorator is called.

logging_instance = logging.getLogger('logger_name')
...

def logging(log_string=''):
    def logging_decorator(func):
        def _wrapper(*args, **kwargs):
            func(*args, **kwargs)
            logging_instance.info(log_string)    # this must be same instance for whole project in any place
        return _wrapper
    return logging_decorator

class MyClass:
    @logging('Action started')
    def action():
        pass    # any action

Are there any ready-made design patterns for such a case?

Upvotes: 0

Views: 1480

Answers (1)

drx
drx

Reputation: 166

It is not created everytime, a logger is preserved and returned whenever getLogger is called with the same name. As logging documentation states:

Loggers have the following attributes and methods. Note that Loggers should NEVER be instantiated directly, but always through the module-level function logging.getLogger(name). Multiple calls to getLogger() with the same name will always return a reference to the same Logger object.

Upvotes: 3

Related Questions