Logging as the caller module in Python

后端 未结 3 603
离开以前
离开以前 2021-01-25 03:21

I have the following application structure:

./utils.py
def do_something(logger=None):
    if not logger:
        logger = logging.getLogger(__name__)

    print(         


        
3条回答
  •  天命终不由人
    2021-01-25 03:35

    Passing the logger as an argument looks fine to me. But if you have many calls to do_something then passing the same logger in each call is not only too verbose but prone to errors --you might pass the wrong logger by mistake. Also, while you do need to make do_something aware of the logger, doing it at the point where you are calling it probably does not make sense --you want to do something, not mess with loggers. OOP to the rescue: make do_something a method of a class and pass the logger when instantiating the class, then you do not need to pass it to the method.

    # utils.py
    class UsefulObject:
        def __init__(self, logger):
            self._logger = logger
    
        def do_something(self):
            print('hello')
            self._logger.debug('test')
    

    Now in the client module you create an instance of UsefulObject and you can call .do_something on it without passing the logger every time.

    # one.py
    from utils import UsefulObject
    logger = logging.getLogger(__name__)
    useful_object = UsefulObject(logger)  # do this once
    # ...
    useful_object.do_something()  # do this many times, do not pass the logger
    

提交回复
热议问题