用于异常日志记录的 Python 记录器处理程序配置



我写了这段代码来从xml文档中获取命名空间。 我正在尝试处理异常,并将完整跟踪写入日志。但是,跟踪没有在日志中使用自定义消息写入(尽管我可以在屏幕上看到它(。

我相信,我在记录器处理程序配置中缺少一些东西。 我们需要处理任何特定的配置吗? 以下是我到目前为止的记录器配置。

任何帮助将不胜感激。!

logger = logging.getLogger(__name__)
hdlr = logging.FileHandler(r'C:link.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
def get_ns(xmlroot):
"""Retrieve XML Document Namespace """
try:
logger.info("Trying to get XML namespace detail")
nsmap = xmlroot.nsmap.copy()
logger.info("Creating XML Namespace Object, {0}".format(nsmap))
nsmap['xmlns'] = nsmap.pop(None)
except (KeyError, SystemExit):
logging.exception("XML files does not contain namespace, Halting Program! ")
sys.exit()
else:
for ns in nsmap.values():
logger.info("Retrieved XML Namespace {0}".format(ns))
return ns

屏幕上的输出:

ERROR:root:XML files does not contain namespace, Halting Program! 
Traceback (most recent call last):
File "C:link.log", line 28, in get_ns
nsmap['xmlns'] = nsmap.pop(None)
KeyError: None

更改

logging.exception("XML files does not contain namespace, Halting Program! ")

logger.exception("XML files does not contain namespace, Halting Program! ")

由于您logger已配置为写入文件C:link.log.

使用logging.exception使用"根记录器",默认情况下输出到控制台。

最新更新