下面的例子會使它更清楚一點。您需要設置的主要級別是logger
對象。您可以通過調用getEffectiveLevel方法來檢查logger
級別。
def setup():
logger = logging.getLogger('mytest')
formatter = logging.Formatter('%(asctime)s %(message)s')
fileHandler = logging.FileHandler('mylog.log')
fileHandler.setLevel(logging.DEBUG)
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
logger.critical("before setting Level on logger, effective level = {}".format(
logger.getEffectiveLevel()))
#THIS WON'T BE logged becuse logger level is WARN
# and DEBUG < WARN
logger.debug('logging debug before setting debug level')
logger.setLevel(logging.DEBUG)
logger.critical("after setting Level on logger, effective level = {}".format(
logger.getEffectiveLevel()))
#THIS WILL BE logged in mylog.log because DEBUG >= DEBUG
logger.debug('logging debug after setting debug level')
fileHandler.setLevel(logging.CRITICAL)
#THIS WON'T BE logged in mylog.log because fileHandler level is CRITICAL--->
# and DEBUG < CRITICAL
logger.debug("this won't be printed in mylog.log")
#THIS WILL BE logged in mylog.log BECAUSE CRITICAL >= CRITICAL--->
logger.critical("logging at critical level")
您需要對'logger'變量調用'setLevel' – kmad1729