Today I learned how to use
rich for beautiful tracebacks in the REPL and how to use it to log prettier exceptions.
comes with an option that lets you modify the way your tracebacks are printed in the REPL.
In order to use it, you only need to install the traceback handler that comes with
Here is the code you need:
from rich import traceback traceback.install
If you are in the REPL, the second line will produce some output:
>>> from rich import traceback >>> traceback.install() <built-in function excepthook>
traceback.install “returns the previous exception handler that was replaced”.
You can safely ignore that or, as I prefer to do it, just use a throwaway variable:
>>> from rich import traceback >>> _ = traceback.install()
Let me show you what the
traceback handling does for you.
First, let us define a couple of dummy functions:
def f(): return 1 / 0 def g(): return 1 + f()
Notice how calling
f will always raise an error.
traceback installed, the error looks like this:
If you install
traceback in your console, the output is now much more beautiful and, above all, easier to read:
richfor logging exceptions
Yesterday I wrote about how you can use
rich for beautiful logging.
Today I learned that you can also make it so that the exception logging has the nice colours of
All you need to do is set
rich_tracebacks=True when instantiating the logging handler
If we go back to the short example I had in the previous article,
I can modify
RichHandler to set
import logging from rich.logging import RichHandler FORMAT = "%(message)s" logging.basicConfig( level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler(rich_tracebacks=True)], # <- not sets rich_tracebacks ) # ...
Before the modification, running the program would generate logging output that contains a pretty plain Python exception. I included a screenshot here:
However, by setting
rich_tracebacks=True, the exception that is logged is also rendered beautifully:
rich is the gift that just keeps on giving...
I wonder what I'll learn tomorrow!
That's it for now! Stay tuned and I'll see you around!
I hope you learned something new! If you did, consider following the footsteps of the readers who bought me a slice of pizza 🍕. Your small contribution helps me produce this content for free and without spamming you with annoying ads.
rich.loggingdocumentation, https://rich.readthedocs.io/en/latest/logging.html [last accessed 28-04-2022];
rich.tracebackdocumentation, https://rich.readthedocs.io/en/latest/reference/traceback.html [last accessed 28-04-2022];