您好我正在尝试在python上启用日志,并且由于某种原因没有记录任何内容。有人可以帮我解决我犯的错误。
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.debug('hello world')
答案 0 :(得分:0)
以下示例将使其更加清晰。您需要设置的主要级别是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")