Rich Logger: Enhance Your Python Logging Experience with Rich
The rich-logger package is a fantastic tool for anyone looking to enhance their logging in Python with colorful and expressive logs. It harnesses the power of the Rich library to provide beautifully formatted logs that are easy to read and understand. In this blog post, we will explore dozens of APIs provided by rich-logger along with comprehensive code snippets. We will also showcase a small application that employs these APIs.
Getting Started
To get started, you need to install both rich
and rich-logger
pip install rich rich-logger
Basic Usage
Basic usage of rich-logger can be achieved with just a few lines of code:
import logging
from rich_logger import RichLogger
logger = RichLogger(name="my-logger")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
Customizing Log Levels
Customize the log levels as per your requirements:
logger.setLevel(logging.DEBUG)
logger.debug("This is a debug message")
Adding Contextual Information
Rich-logger supports adding contextual information such as filenames, function names, and line numbers:
logger.info("This is an info message", extra={"user": "John Doe", "location": "Server 1"})
Log Exception Tracebacks
You can also log exceptions with full tracebacks:
try:
1 / 0
except ZeroDivisionError:
logger.exception("An exception occurred")
Advanced Formatting
Take advantage of the rich formatting capabilities to visualize better:
logger.info("[bold green]Success:[/] The operation completed successfully!")
Creating a Logger for Your Application
Here is a small example of how you can use rich-logger in an application:
import logging
from rich_logger import RichLogger
logger = RichLogger(name="app-logger", level=logging.DEBUG)
def divide(a, b):
try:
result = a / b
logger.info(f"Division result: {result}")
return result
except ZeroDivisionError:
logger.exception("Division by zero")
return None
if __name__ == "__main__":
divide(10, 2)
divide(10, 0)
With rich-logger, your Python applications will have log messages that are not only colorful but also packed with contextual information and ready for production use.
Hash: be56dc1ea03dcaef52c193795f133d3c403d287db10988af6243216ce36588c4