Prettier logging with Rich
If you are a Python developer you may spend a large part of your day reading log output that looks like this:
Front end tools like the Chrome developer console have far superior rendering for logs, but in the back-end we're stuck with an ancient technology that is older than most of the readers of this blog. I'm talking of course of the terminal which is likely to be the primary interface to back-end development until I retire.
Still I think we can do a little better. I wanted to use my terminal rendering library, Rich to render log output that is easier on the eye. The results are promising:
There are a few things going on here. Important fields are rendered in their own column to make it easier to scan. To reduce visual clutter, the time field is only rendered if it changes and I've set the date format to time only, which is fine for local development (if you forget what day it is you need a vacation). The message column has some syntax highlighting applied to it, tuned for web development, but more importantly it is word-wrapped. Finally there is a column for the python file and line that called the log method.
This would be my ideal logging for web-development, your mileage may vary and you may want to tune it for your domain.
You can try this yourself by configuring logging to use rich.logging.RichHandler
.
Rich is still in active development and not ready for a 1.0 release. If you want to use it anger, best pin the current version for now.
Hi Will,
I wonder if there's a way to enable pretty json printing in the logger?
If not:
Thanks in advance, and thank you so much for providing such amazing tools! I look forward to seeing what you do next.
Best, Dan
Not auto-detection, but if you know when you're going to be logging JSON, I've found this works all right (assuming you're using
rich.logging,RichHandler
, of course):JSON()
runsJSONHighlighter()
over the JSON on input, which you'd maybe think would do the job, but that highlighting gets stripped out by the default highlightingRichHandler
does, so you still have to pass aJSONHighlighter
yourself via theextra
argument. (Also, if you don't get the text via.text
, theJSON
object just logs itself viarepr
as<rich.json.JSON object at etc.>
.)I'll give this strategy a try where applicable--thank you for your reply!
Hey Will!! It's a cool module that you've created!! I extensively use this in my projects!! But, I'm looking for a way to save the logs displayed on the terminal with the exact rich highlights and formats. Can you share a way on how to do that??