Logging

Basics of the standard library logging module
.
├── script.py
└── my_library
    ├── __init__.py
    ├── module.py
    └── submodule.py

script.py

import os
import logging
from datetime import datetime

from my_library import module

# Do not specify __name__ to use root log level
logger = 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 logging
from my_library import submodule


def main():
    logger = logging.getLogger("__main__")
    logger.info("Log message from main function in module.py")
    submodule.bar()


if __name__ == "__main__":
    main()

submodule.py

import logging


def bar():
    logger = logging.getLogger()
    logger.info("Hello from submodule.py in function bar()")