Today I learned how you can do beautiful console logging by using the module rich
.
The standard way to do logging in Python is by using the module logging
that comes in the standard library.
To do beautiful console logging with very little effort you just need to use the
rich
package.
It can be as simple as copying the “setup” code included in the documentation:
import logging
from rich.logging import RichHandler
FORMAT = "%(message)s"
logging.basicConfig(
level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]
)
log = logging.getLogger("rich")
log.info("Hello, World!")
rich
and RichHandler
Using the setup code above, I wrote a little script:
import logging
from rich.logging import RichHandler
FORMAT = "%(message)s"
logging.basicConfig(
level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]
)
log = logging.getLogger("rich")
log.info("Logging set up.")
def division(a, b):
log.debug(f"Dividing {a} by {b}.")
try:
return a / b
except ZeroDivisionError:
log.exception("Oh noes!")
division(3, 2)
division(5, 0)
If I run this script, here is the output I get:
Your exact colours might be different, but the essence of your output will be just like mine (I wrote an article on how I set up my terminal to use a nice colour scheme):
logging
, but rich
colours them);All of this at the distance of a copy & paste operation! Isn't this amazing?
This is a very simple example of what you can do with logging
+ rich
.
You might want to check their documentations (links in the references) to learn more!
That's it for now! Stay tuned and I'll see you around!
+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!
My book “Pydon'ts” teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here 🐍🚀.
rich
documentation, https://rich.readthedocs.io/en/latest/logging.html [last accessed 27-04-2022];logging
, https://docs.python.org/3/library/logging.html [last accessed 27-04-2022];