Sometimes I think Python has the weirdest logic to it.
Why does the Python logger function fail to log a single thing when it’s in a def
function but logs everything when it’s outside a def
function?
I have created a MRE as a tester, but I see no reason as to why it chooses to log everything outside a def
function but nothing inside a def
function.
My logging configuration file is correctly imported, and everything that is logged outside of the test_logging()
function is logged & logged to the correct .log
file.
As you cansee the setup in the logging_config
file is set to DEBUG
so it will catch everything.
This is my setup, starting with the logging configuration file:
import logging
#<ROOT>.logging_config
def logging_configuration(filename="support/app.log"):
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[logging.FileHandler(filename),
logging.StreamHandler()])
This is the MRE test:
#support.views
from <ROOT>.logging_config import logging_configuration
import logging
logging_configuration()
logger = logging.getLogger(__name__)
logger.debug("Logging setup complete...")
logger.debug("Debug message not in a def function")
logger.info("Info message not in a def function")
logger.warning("Warning message not in a def function")
logger.error("Error message not in a def function")
logger.critical("Critical message not in a def function")
def test_logging():
logger.debug("Debug message")
logger.info("Info message")
logger.warning("Warning message")
logger.error("Error message")
logger.critical("Critical message")
print("You should see this message")
if __name__ == "__main__":
test_logging()
These are the logs:
2024-08-07 09:53:55,090 - support.views - DEBUG - Logging setup complete...
2024-08-07 09:53:55,091 - support.views - DEBUG - Debug message not in a def function
2024-08-07 09:53:55,091 - support.views - INFO - Info message not in a def function
2024-08-07 09:53:55,091 - support.views - WARNING - Warning message not in a def function
2024-08-07 09:53:55,092 - support.views - ERROR - Error message not in a def function
2024-08-07 09:53:55,092 - support.views - CRITICAL - Critical message not in a def function
To me, it makes absolutely no sense. What am I missing here?