简体   繁体   中英

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)

This generates a black and white traceback of the exception. I ran from a notebook, is there a way to output this with the usual color scheme seen in jupyter notebook tracebacks?

When run in Jupyter, this will print what you should be seeing now, followed by the colored, full traceback below that :

# 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()))

I've tested this in vanilla JupyterLab and current classic notebook interface (soon to be called more along the line of the 'document-oriented interface' with V7 of the Jupyter Notbeook).

Key additions are importing sys so can use sys.exc_info() and bringing in ultratb that apparently is used to handle tracebacks in Jupyter and then sending the traceback to IPython.core.ultratb.VerboseTB() .

Solution based mainly on here . I put a lot of the associated resources in the comments at the top of the code block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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