One class instance used automatically throughout p

2019-06-11 12:42发布

The python logging module once imported and instantiated will be so across the process, inside all modules and threads. How did they achieve that effect?

Example:

myapp.py

import logging
import mylib

def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('Started')
    mylib.do_something()
    logging.info('Finished')

if __name__ == '__main__':
    main()

mylib.py

import logging

def do_something():
    logging.info('Doing something')

myapp.log

INFO:root:Started
INFO:root:Doing something
INFO:root:Finished

1条回答
地球回转人心会变
2楼-- · 2019-06-11 13:35

When a module is imported for the first time, the loaded module object is put into sys.modules. Later imports will then find the module object and not reload the module.

The logging module has a bunch of module attributes which hold the state of logging configuration after the first import.

查看更多
登录 后发表回答