Last active
March 11, 2024 04:46
-
-
Save ptmcg/6d42bd63dc42008653494ea49f54e1df to your computer and use it in GitHub Desktop.
Demonstration of setting log level in a handler overrides setting log level in a logger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Demonstrates that setting the log level in a handler overrides any setting of log level in the logger | |
# | |
# The purpose of this is to support adding handlers that take extra action or route log messages to other | |
# destinations for any logs at higher levels. For instance, creating and adding a handler to the root | |
# logger where the handler's level is set to ERROR, and streams its logs to a notification service queue. | |
# Even if the logger's level is set to a lower level of logging, the specialized handler only routes | |
# ERROR or higher log messages to the notification service. | |
# | |
# The problem arises if the handler that is set to a particular log level is the root logger's sole | |
# stdout handler. In this case, it becomes difficult to change the log level on the logger, because the | |
# level set on its handler takes precedence. | |
# | |
import sys | |
import logging | |
# set up root logger as if running logging.basicConfig() | |
root_log = logging.getLogger() | |
root_handler = logging.StreamHandler(sys.stdout) | |
root_handler.setFormatter( | |
logging.Formatter( | |
fmt='%(asctime)s.%(msecs)03d %(levelname)s [%(name)s] %(message)s', | |
datefmt='%Y-%m-%d %H:%M:%S' | |
) | |
) | |
root_log.addHandler(root_handler) | |
# uncomment this line to see that the handler level overrides setting the logger level | |
# root_handler.setLevel(logging.ERROR) | |
root_log.setLevel(logging.DEBUG) | |
log = logging.getLogger(__name__) | |
log.setLevel(logging.DEBUG) | |
log.info("log message") | |
sublog = logging.getLogger(__name__ + ".sub") | |
# sublog.info("sublog message") | |
# sublog = LA(sublog) | |
sublog.info("sublog message") | |
sublog.info("sublog message") | |
other_log = logging.getLogger("other") | |
other_log.setLevel(logging.DEBUG) | |
other_log.info("other_log message") | |
other_log.info("other_log message") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment