import osimport loggingfrom datetime import datetimefrom my_library import module# Do not specify __name__ to use root log levellogger = logging.getLogger(__name__)logger.setLevel(logging.INFO)formatter = logging.Formatter("%(asctime)s : %(msecs)04d : %(name)s : %(levelname)s : %(message)s", datefmt="%Y-%m-%d %H:%M:%S",)log_file =f"log_{datetime.now().strftime('%Y-%m-%d_%H%M%S')}.log"stream_handler = logging.StreamHandler()stream_handler.setFormatter(formatter)file_handler = logging.FileHandler(filename=log_file)file_handler.setFormatter(formatter)logger.addHandler(stream_handler)logger.addHandler(file_handler)logger.info("Begin my test module")module.main()os.remove(log_file)
2022-12-17 06:03:54 : 0441 : __main__ : INFO : Begin my test module
2022-12-17 06:03:54 : 0443 : __main__ : INFO : Log message from main function in module.py
2022-12-17 06:03:54 : 0444 : __main__ : INFO : Hello from submodule.py in function bar()
module.py
import loggingfrom my_library import submoduledef main(): logger = logging.getLogger("__main__") logger.info("Log message from main function in module.py") submodule.bar()if__name__=="__main__": main()
submodule.py
import loggingdef bar(): logger = logging.getLogger() logger.info("Hello from submodule.py in function bar()")