Logging as the caller module in Python

后端 未结 3 607
离开以前
离开以前 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:42

    Variable logger being a global, can be accessed from inside do_something() function like this:

    logger = logging.getLogger(__name__)
    def do_something():
        x = logger
    

    After reading this carefully:

    What's the common solution for this type of recipe, when one function is used all over the code base but the loggers should be of those calling the function?

    In simple english would be:

    How to access global variable logger from imported function do_something()?

    I conclude that there is no other way!
    You have to pass logger as an argument for this particular case.

    from utils import do_something
    logger = logging.getLogger(__name__)
    
    do_something()  # logger global is not visible in do_something()
    do_something(logger=logger)  # the only way
    

提交回复
热议问题