Skip to main content

Pretty Pie Log

A feature-rich, thread-safe Python logging utility that provides colorized console output with customizable formatting, JSON details support, and function execution tracking.

PyPI version Downloads Supported Versions License: MIT

Installation

pip install pretty-pie-log

Features

  • Colorized Output: Customizable colors for different log levels and components, including timestamp, file path, and details.
  • Thread-Safe: Built-in thread safety for reliable logging in multi-threaded applications.
  • Timezone Support: Configurable timezone for timestamp display (default: UTC).
  • Automatic Path Detection: Detects relative file paths based on the project root.
  • Error Trace Integration: Optionally include full error trace details for exceptions.
  • Function Execution Tracking: Decorator for logging function entry, exit, arguments, and results with configurable log levels.
  • File Logging: Configurable rotating file logging with size limits and backup files. Several processes (for example gunicorn workers) can share one log file.
  • Customizable Formatting: Adjust padding for timestamps, log levels, file paths, and other components.
  • Enhanced Log Details Serialization: Handles non-serializable objects in logs by converting them into readable formats.
  • Default Colors and Settings: New fields for default log colors and detailed customization.
  • Global Context Support: For request tracing and correlation.

Quick Start

from pretty_pie_log import PieLogger, PieLogLevel

# Create a logger instance
logger = PieLogger(
    logger_name="my_app",
    timezone="America/New_York",  # Optional: Set specific timezone
    minimum_log_level=PieLogLevel.INFO,  # Optional: Set minimum log level
    log_to_file=True,  # Optional: Enable file logging
)

# Basic logging methods
logger.info("Application started")
logger.debug("Debug message", details={"user_id": 123})
logger.warning("Warning message")
try:
    raise ValueError("Something went wrong")
except ValueError:
    logger.error("Error occurred", print_exception=True)  # Includes error trace
logger.critical("Critical error", details={"error_code": 500})


# Function execution tracking
@logger.log_execution(
    start_message="Starting data processing",
    end_message="Processing complete",
    print_args_at_start=True,
    print_result_at_end=True
)
def process_data(data):
    return {"processed": len(data)}


process_data([1, 2, 3, 4, 5])

Output

image


Detailed Configuration

Logger Initialization

The logger is highly customizable with numerous options:

from pretty_pie_log import PieLogger, PieLogLevel
from colorama import Fore

logger = PieLogger(
    logger_name="my_app",  # Unique identifier for the logger

    # Optional Timezone and Formatting Parameters
    timezone="America/New_York",  # Defaults to UTC if not specified
    timestamp_padding=25,  # Width of timestamp field
    log_level_padding=10,  # Width of log level field
    file_path_padding=30,  # Width of file path field

    # Optional Color Configuration
    debug_log_color=Fore.CYAN,
    info_log_color=Fore.GREEN,
    warning_log_color=Fore.YELLOW,
    error_log_color=Fore.RED,
    critical_log_color=Fore.MAGENTA,
    timestamp_log_color=Fore.WHITE,
    file_path_log_color=Fore.WHITE,
    details_log_color=Fore.LIGHTWHITE_EX,

    # Enhanced Logging Options
    colorful=True,  # Enable/disable colored output
    default_log_color=Fore.WHITE,  # Fallback color when colorful is False
    details_indent=2,  # JSON indentation spaces
    minimum_log_level=PieLogLevel.INFO,  # Minimum logging level

    # Rotating File Logging
    log_to_file=True,  # Enable/disable file logging
    relative_log_directory_path="logs",  # Relative to the file that creates the logger; absolute paths work too
    log_file_size_limit=32 * 1024 * 1024,  # Max log file size (32 MB)
    max_backup_files=10,  # Number of backup log files to keep (default 1; 0 turns rotation off)

    # Global Context Options
    global_context=False  # Enable/disable global context logging
)

Output using the above configuration

image

Logging Methods

All logging methods support the following parameters:

logger.info(
    message="Main log message",  # Required: Main text of the log
    details={"key": "value"},  # Optional: Additional data to include (now supports any data type)
    print_exception=True,  # Optional: Include stack trace if an exception occurred
    colorful=False  # Optional: Override global color settings for this log
)

message is written as-is, newlines included, so put untrusted input in details, which is JSON-escaped.

Enhanced details Parameter

The details parameter, which previously supported only dict, now supports any data type, making it more versatile for structured and unstructured data logging.

  • Supported Data Types:
    • dict: Ideal for key-value pairs or structured data (e.g., {"user_id": 123, "status": "active"})
    • list/tuple: For sequences of data (e.g., [1, 2, 3])
    • set: For unique collections (e.g., {"item1", "item2"})
    • str, int, float, bool: Simple data types
    • None: To explicitly log the absence of details
    • Custom Objects: Non-serializable objects will automatically be converted into readable strings.

Example Usage

# Logging structured data
logger.info(
    message="User login attempt",
    details={"user_id": 123, "status": "success"}
)

# Logging a list of items
logger.debug(
    message="Processing items",
    details=[1, 2, 3, 4, 5]
)


# Logging a custom object
class User:
    def __init__(self, user_id, name):
        self.user_id = user_id
        self.name = name

    def __str__(self):
        return f"User(user_id={self.user_id}, name={self.name})"


user = User(123, "John Doe")

logger.warning(
    message="Custom object logged",
    details=user
)

# Logging without additional details
logger.error(
    message="Critical failure occurred",
    details=None
)

Output:

image

Automatic Serialization

If the details contain non-serializable objects (e.g., custom classes), the logger will automatically convert them into strings, ensuring the logs remain readable without raising serialization errors.

For example:

class ComplexObject:
    pass


logger.debug(
    message="Logging complex object",
    details=ComplexObject()
)

Console Output

2024-11-30 10:52:00.125   DEBUG      ./../example.py:17             : Logging complex object
"<__main__.ComplexObject object at 0x0000020FD4484A90>"

This enhancement ensures compatibility with diverse use cases while maintaining structured logging capabilities.


Log Levels

The package provides five standard log levels:

  • PieLogLevel.DEBUG (10)
  • PieLogLevel.INFO (20)
  • PieLogLevel.WARNING (30)
  • PieLogLevel.ERROR (40)
  • PieLogLevel.CRITICAL (50)

Function Execution Tracking

The log_execution decorator provides detailed monitoring of function execution:

@logger.log_execution(
    start_message="Starting task...",  # Optional: Custom start message
    end_message="Task complete.",  # Optional: Custom end message
    print_args_at_start=True,  # Log function arguments
    print_result_at_end=True,  # Log function return values
    start_message_log_level=PieLogLevel.DEBUG,  # Customizable log levels
    end_message_log_level=PieLogLevel.INFO
)
def task(arg1, arg2):
    return "result"

The decorator also works on async def functions. If the function raises, an Exception in <name> error with the traceback is logged and the exception is re-raised.

Console Output

image


Dependencies

  • Python 3.7+
  • colorama
  • concurrent-log-handler
  • pytz

Contributing

Contributions are welcome! Submit your ideas or pull requests.


License

MIT License

Usage

Basic Usage

from pretty_pie_log import PieLogger, PieLogLevel

# Initialize logger
logger = PieLogger(
    logger_name="my_app",
    timezone="UTC",
    minimum_log_level=PieLogLevel.INFO
)

# Log messages
logger.debug("Debug message")
logger.info("Info message")
logger.warning("Warning message")
logger.error("Error message")
logger.critical("Critical message")

Context Management

The logger supports context for request tracing and correlation. When enabled, the context will be included in all log messages.

Context is kept per thread and per asyncio task, so concurrent requests never see each other's values. A thread does not inherit values set in another thread: call add_context inside the thread that handles the request.

# Initialize logger with context enabled
logger = PieLogger(
    logger_name="my_app",
    global_context=True  # Enable context logging
)

# Add context information
logger.add_context("request_id", "12345")
logger.add_context("user_id", "user123")

# Log messages will include the context
logger.info("Processing request")

# Remove specific context
logger.remove_context("user_id")

# Clear all context
logger.clear_context()

Function Execution Logging

@logger.log_execution(
    start_message="Starting task...",  # Optional: Custom start message
    end_message="Task complete.",  # Optional: Custom end message
    print_args_at_start=True,  # Log function arguments
    print_result_at_end=True,  # Log function return values
    start_message_log_level=PieLogLevel.DEBUG,  # Customizable log levels
    end_message_log_level=PieLogLevel.INFO
)
def task(arg1, arg2):
    return "result"

Console Output

image

Metadata

Release files for pretty-pie-log 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pretty-pie-log 0.4.0
File Size Uploaded Provenance Actions
pretty_pie_log-0.4.0.tar.gz 16.4 kB With provenance Details for pretty_pie_log-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pretty-pie-log 0.4.0
File Interpreter ABI Platform Actions
pretty_pie_log-0.4.0-py3-none-any.whl Python 3 none any Details for pretty_pie_log-0.4.0-py3-none-any.whl

Total release size: 30.0 kB

Release files / pretty_pie_log-0.4.0.tar.gz

Download URL pretty_pie_log-0.4.0.tar.gz
Size 16.4 kB
Tags Source
SHA-256 checksum
How to use checksums
93d7475d5f7775d22b53c534d2515460410bd96cbe225ab91175cdc1ec02deb5
BLAKE2b-256 checksum
How to use checksums
15d272ef9eed0d0c052f2f1325356192163aa578594000c33945f66d13590942
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Release files / pretty_pie_log-0.4.0-py3-none-any.whl

Download URL pretty_pie_log-0.4.0-py3-none-any.whl
Size 13.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0fb573eff42d2ca7f7544f968766e07b42ffc0fc57cbe5365e2144102b8f2261
BLAKE2b-256 checksum
How to use checksums
541356cc8e958c0a052315455077c3af0d9f48617ef4f0de2da452059d9f0b56
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Security for pretty-pie-log 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pretty_pie_log-0.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page