[英]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.