Hi,
I’m trying to understand logging. I’m following How to configure and use logging | Django documentation | Django and it shows there how to configure a logger that logs everything (logger ""
) to a file.
I tried that and added the setting below to my settings.py, which made me notice some unexpected behaviour.
LOGGING = {
"version": 1, # the dictConfig format version
"disable_existing_loggers": False, # retain the default loggers
"formatters": {
"verbose": {
"format": "{asctime} {levelname:<8} {module:<12} | {message}",
"style": "{",
},
"simple": {
"format": "{levelname} {message}",
"style": "{",
},
},
"handlers": {
"file": {
"class": "logging.FileHandler",
"filename": "general.log",
"formatter": "verbose",
},
},
"loggers": {
"": {
"handlers": ["file"],
"level": "DEBUG",
},
},
}
In my view I am logging the following.
import logging
logger = logging.getLogger(__name__)
logger.debug("MY LOGGER: DEBUG")
logger.info("MY LOGGER: INFO")
logger.warning("MY LOGGER: WARNING")
logger.error("MY LOGGER: ERROR")
logger.critical("MY LOGGER: CRITICAL")
Without the setting, the following gets logged:
Console
MY LOGGER: WARNING
MY LOGGER: ERROR
MY LOGGER: CRITICAL
[23/Apr/2024 22:57:17] "GET / HTTP/1.1" 200 9515
general.log
But with the setting, the following gets logged:
Console
[23/Apr/2024 22:58:43] "GET / HTTP/1.1" 200 9515
general.log
2024-04-23 22:58:43,653 DEBUG views | MY LOGGER: DEBUG
2024-04-23 22:58:43,653 INFO views | MY LOGGER: INFO
2024-04-23 22:58:43,653 WARNING views | MY LOGGER: WARNING
2024-04-23 22:58:43,653 ERROR views | MY LOGGER: ERROR
2024-04-23 22:58:43,653 CRITICAL views | MY LOGGER: CRITICAL
Now my understanding is that the setting I added is additive. The docs state that “a logger can forward messages to multiple handlers, so the relation between loggers and handlers is many-to-many.” And the logger name does not override an existing named logger, such as django.server
.
So why does my setting remove the logs from the console logger? I was expecting my five test log messages to appear in both, the console and the file.