繁体   English   中英

在 jupyter notebook 中使用着色而不是黑白打印 logging.exception

[英]printing logging.exception in jupyter notebook with coloring instead of black and white

a = []
import logging 
try: 
    a[1]
except Exception as e: 
    logging.exception(e)

这会生成异常的黑白回溯。 我从一个笔记本跑了,有没有办法用 jupyter notebook tracebacks 中常见的配色方案来实现 output?

在 Jupyter 中运行时,这将打印您现在应该看到的内容,然后是下面的彩色完整回溯

# based on https://docs.python.org/3/library/traceback.html and
# https://stackoverflow.com/a/49410847/8508004 and https://stackoverflow.com/a/3702847/8508004 and bottom of https://stackoverflow.com/a/53779794/8508004 (Although I found
# that didn't actually need `exc_info=True` in `logging.exception(e, exc_info=True)`?) , but still pertinent because states "with tracebacks as well, because log.exception produces logs of only one level - ERROR."
# (Other things had also said logging goes to stderr channel -- related info at https://stackoverflow.com/q/58971197/8508004 and in [Creating Beautiful Tracebacks with Python's Exception Hooks](https://martinheinz.dev/blog/66))
a = []
import sys
import logging 
import IPython.core.ultratb  #based on https://stackoverflow.com/a/49410847/8508004
tb = IPython.core.ultratb.VerboseTB() #based on https://stackoverflow.com/a/49410847/8508004

try: 
    a[1]
except Exception as e:
    logging.exception(e)
    print(tb.text(*sys.exc_info()))

我已经在 vanilla JupyterLab 和当前的经典笔记本界面(很快将被更多地称为 Jupyter Notbeook 的 V7 的“面向文档的界面”)中对此进行了测试。

关键添加是导入sys以便可以使用sys.exc_info()并引入显然用于处理ultratb中的回溯的 ultratb,然后将回溯发送到IPython.core.ultratb.VerboseTB()

解决方案主要基于这里 我在代码块顶部的注释中放置了很多相关资源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM