Skip to main content

A loguru sink that uses rich to format log messages.

Project description

loguru-rich-sink

A beautiful, feature-rich sink for Loguru that leverages the Rich library to display stunning, gradient-colored log messages in styled panels.

Features

โœจ Beautiful Terminal Output - Log messages displayed in Rich panels with gradient colors
๐ŸŽจ Level-Specific Styling - Each log level has unique colors and gradients
๐Ÿ“Š Run Tracking - Optional tracking and incrementing of run numbers
๐Ÿ“ Trace File Logging - Write detailed trace logs when run tracking is enabled
๐Ÿ”ง Highly Customizable - Configure console, styles, and log formats
๐Ÿ Type-Safe - Full type hints for better IDE support
โšก Easy Integration - Drop-in replacement for standard loguru sinks

Installation

pip install loguru-rich-sink

Or with uv:

uv add loguru-rich-sink

Requirements

  • Python >= 3.13
  • loguru >= 0.7.3
  • rich >= 15.0.0

Quick Start

from loguru import logger
from loguru_rich_sink import RichSink

# Add the RichSink to your logger
logger.remove()
logger.add(RichSink(), format="{message}")

# Start logging with beautiful output!
logger.info("Hello, World!")
logger.success("Operation completed successfully!")
logger.warning("This is a warning message")
logger.error("An error occurred")

Usage

Basic Usage

The simplest way to use loguru-rich-sink:

from loguru import logger
from loguru_rich_sink import RichSink

logger.remove()
logger.add(RichSink(), format="{message}")

logger.trace("Trace message")
logger.debug("Debug message")
logger.info("Info message")
logger.success("Success message")
logger.warning("Warning message")
logger.error("Error message")
logger.critical("Critical message")

Custom Console

Pass your own Rich console for more control:

from rich.console import Console
from loguru import logger
from loguru_rich_sink import RichSink

# Create a custom console
console = Console(width=120, force_terminal=True)

# Use it with RichSink
logger.remove()
logger.add(RichSink(console=console), format="{message}")

Logger Helper

The package includes a helper that removes Loguru's default handlers and configures a RichSink console handler:

from loguru_rich_sink import get_logger

logger = get_logger()

logger.info("Logged with Rich formatting!")

This configuration:

  • Displays logs in the console using RichSink with beautiful formatting
  • Enables backtrace and diagnose for better debugging

Pass track_run=True to also persist a run counter and write detailed trace logs to logs/trace.log:

from loguru_rich_sink import get_logger

logger = get_logger(track_run=True)

logger.info("Logged to the console and trace file!")

Run Tracking

Run tracking is available through RichSink methods:

from loguru_rich_sink import RichSink

sink = RichSink(track_run=True)

# Initialize run tracking storage (creates logs directory and run file)
current_run = sink.setup()
print(f"Current run: {current_run}")

# Increment run number
next_run = sink.increment()
print(f"Next run: {next_run}")

When track_run=True, run numbers are displayed in the subtitle of each log panel.

Log Levels and Styling

Each log level has its own distinct visual style:

Level Colors Style
TRACE Gray gradient Dim
DEBUG Cyan/teal gradient Default
INFO Blue gradient Default
SUCCESS Green gradient Bold
WARNING Yellow/orange gradient Bold
ERROR Orange/red gradient Bold
CRITICAL Red/magenta gradient Bold

API Reference

RichSink

The main sink class for loguru.

class RichSink:
    def __init__(
        self,
        track_run: bool = False,
        run: int | None = None, 
        console: Console | None = None
    ) -> None:

Parameters:

  • track_run (bool): Whether to track and persist the run count.
  • run (int | None): Optional initial run number.
  • console (Console | None): A Rich Console instance. If None, creates a new one.

Usage:

sink = RichSink(run=1, console=my_console)
logger.add(sink, format="{message}")

Helper Functions

get_console

def get_console(
    record: bool = False, 
    console: Console | None = None
) -> Console:

Initialize and return a Rich console with traceback support.

get_logger

def get_logger(
    console: Console | None = None,
    track_run: bool = False,
    handlers: Sequence[dict[str, Any]] | dict[str, Any] | None = None,
) -> Logger:

Get a configured Loguru logger with a Rich console sink. When track_run=True, it also increments the run counter and adds logs/trace.log as a trace-level file sink.

get_progress

def get_progress(console: Console | None = None) -> Progress:

Return a Rich progress bar configured to match the logger output.

find_cwd

def find_cwd(start_dir: Path | None = None, verbose: bool = False) -> Path:

Walk upward from start_dir or the current working directory until a pyproject.toml is found. If none is found, the search stops at the filesystem root.

Constants

LEVEL_STYLES

RichSink.LEVEL_STYLES maps log levels to Rich Style objects:

LEVEL_STYLES: dict[str, Style] = {
    'TRACE': Style(dim=True),
    'DEBUG': Style(color='#aaaaaa'),
    'INFO': Style(color='#00afff'),
    'SUCCESS': Style(bold=True, color='#00ff00'),
    'WARNING': Style(bold=True, color='#ffaf00'),
    'ERROR': Style(bold=True, color='#ff5000'),
    'CRITICAL': Style(color='#ffffff', bgcolor='#ff0000', bold=True),
}

GRADIENTS

RichSink.GRADIENTS maps log levels to color gradients:

GRADIENTS: dict[str, list[str]] = {
    'TRACE': [...],    # Gray gradient
    'DEBUG': [...],    # Cyan gradient
    'INFO': [...],     # Blue gradient
    'SUCCESS': [...],  # Green gradient
    'WARNING': [...],  # Yellow gradient
    'ERROR': [...],    # Orange-red gradient
    'CRITICAL': [...], # Red-magenta gradient
}

Paths

LOGS_DIR: Path  # Path to logs directory
RUN_FILE: Path  # Path to run counter file

Advanced Usage

Custom Formatting

You can customize the log format while still using RichSink:

from loguru import logger
from loguru_rich_sink import RichSink

logger.remove()
logger.add(
    RichSink(),
    format="{message}",
    level="DEBUG",
    backtrace=True,
    diagnose=True,
)

Multiple Sinks

Combine RichSink with other sinks:

from loguru import logger
from loguru_rich_sink import RichSink

# Remove default handler
logger.remove()

# Add Rich console sink
logger.add(RichSink(), format="{message}", level="INFO")

# Add file sink for detailed logs
logger.add(
    "logs/app.log",
    format="{time} | {level} | {message}",
    level="TRACE",
    rotation="10 MB",
)

# Add JSON sink for structured logging
logger.add(
    "logs/app.json",
    format="{message}",
    level="INFO",
    serialize=True,
)

Integration with Existing Projects

If you have an existing project using loguru:

from loguru import logger
from loguru_rich_sink import RichSink

# Keep your existing sinks and add Rich output
# Omit remove() here if you intentionally want to keep existing handlers.
logger.remove()
logger.add(RichSink(), format="{message}", level="INFO")

# Your existing logging code works as-is
logger.info("Now with beautiful Rich formatting!")

Example Output

When run tracking is enabled, logs appear as beautifully formatted panels with the run number in the subtitle:

โ”Œโ”€ INFO | app.py | Line 42 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€ Run 1 | 14:23:45.123 PM โ”€โ”
โ”‚                                                                  โ”‚                           โ”‚
โ”‚  Application started successfully                                โ”‚                           โ”‚
โ”‚                                                                  โ”‚                           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Each log level uses distinct gradient colors and styling to make logs easy to scan and understand.

Running the Demo

To see loguru-rich-sink in action:

python -m loguru_rich_sink

This displays the INFO, SUCCESS, WARNING, ERROR, and CRITICAL demo messages with their respective styling. TRACE and DEBUG records are filtered by the demo's INFO-level console handler.

File Structure

loguru-rich-sink/
โ”œโ”€โ”€ src/
โ”‚   โ””โ”€โ”€ loguru_rich_sink/
โ”‚       โ”œโ”€โ”€ __init__.py      # Package exports
โ”‚       โ”œโ”€โ”€ __main__.py      # Demo/example usage
โ”‚       โ””โ”€โ”€ sink.py          # Core implementation
โ”œโ”€โ”€ logs/                    # Created automatically when run tracking is enabled
โ”‚   โ”œโ”€โ”€ run.txt             # Run counter
โ”‚   โ””โ”€โ”€ trace.log           # Log file
โ”œโ”€โ”€ pyproject.toml          # Project metadata
โ””โ”€โ”€ README.md               # This file

Development

Setting Up Development Environment

# Clone the repository
git clone https://github.com/maxludden/loguru-rich-sink.git
cd loguru-rich-sink

# Install with uv (recommended)
uv sync

# Or install the package in editable mode
pip install -e .

Running Tests

# Run tests
uv run pytest

# Run linting
uv run ruff check .

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

License

This project is open source. Please check the repository for license information.

Credits

Author

Max Ludden
Email: dev@maxludden.com
GitHub: @maxludden

Changelog

v0.0.4

  • Current version
  • Full Python 3.13 support
  • Improved type hints
  • Enhanced documentation

v0.0.3

  • Initial release
  • Core RichSink functionality
  • Run tracking
  • Dual sink setup

Related Projects

  • loguru - Python logging made (stupidly) simple
  • rich - Rich text and beautiful formatting in the terminal

Made with โค๏ธ and Python

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

loguru_rich_sink-0.0.5.tar.gz (28.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

loguru_rich_sink-0.0.5-py3-none-any.whl (11.5 kB view details)

Uploaded Python 3

File details

Details for the file loguru_rich_sink-0.0.5.tar.gz.

File metadata

  • Download URL: loguru_rich_sink-0.0.5.tar.gz
  • Upload date:
  • Size: 28.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for loguru_rich_sink-0.0.5.tar.gz
Algorithm Hash digest
SHA256 24f6a772cccfd2e2efcb31c2af82db8cf585d1e235d31e5da7b3423842367c08
MD5 a790048019365ff373d226f44339212f
BLAKE2b-256 b83c4bdaf2ec5117a0e6a41102b17dd37e0d3bf4bfc2baaa0d34016eb0c93992

See more details on using hashes here.

File details

Details for the file loguru_rich_sink-0.0.5-py3-none-any.whl.

File metadata

  • Download URL: loguru_rich_sink-0.0.5-py3-none-any.whl
  • Upload date:
  • Size: 11.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for loguru_rich_sink-0.0.5-py3-none-any.whl
Algorithm Hash digest
SHA256 e5c9cdc2c2ff0be10117d5623bea7fffd749f0204c0e01928c3265ff2772bec7
MD5 9895d9bfbc6fd0c67989d78736ebc54d
BLAKE2b-256 d96c7f709f4b7fc257fa5105ebba08fcb80f179f26b72870e6c33e7b9ea4cc77

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page