Skip to main content

ctxlog

PyPI version Python versions License Documentation Status

A structured logging library for Python that provides nested, context-rich logs.

This library was inspired by the Canonical Log Lines, which emphasizes the importance of reducing the amount of noise in logs for better observability and debugging. With the addition of log chaining, ctxlog allows to create log trees that can be used to track complex operations and their context, similar to tracing mechanisms.

Features

  • Structured Logging: Structured logs with context fields with optional JSON serialization
  • Context-Rich: Extend the logs with additional context information over the course of an action
  • Log Chaining: Create nested log contexts for tracking complex operations

Documentation

Full documentation is available at ctxlog.readthedocs.io.

Installation

pip install ctxlog

Or with Poetry:

poetry add ctxlog

Quick Start

import ctxlog

# Configure the logger (optional, uses sensible defaults)
ctxlog.configure(
    level="debug",  # or ctxlog.LogLevel.INFO
    timefmt="iso",  # ISO8601 format
    utc=True,  # Use UTC for timestamps
)

# Create a logger instance
logger = ctxlog.get_logger("example")

# Simple logging
logger.debug("This is a simple debug log")
logger.info("This is a simple info log")
logger.warning("This is a simple warning log")
logger.error("This is a simple error log")
logger.critical("This is a simple critical log")

# Structured logging with context
log = logger.ctx(user_id="user123", action="login").info("User logged in")

# Exception handling
try:
    # Some code that might raise an exception
    result = 1 / 0
except Exception as e:
    log = logger.new("exception_example").ctx(dividing=1, by=0)
    log.exc(e).error("Division failed")

# Log chaining for complex operations
def process_data(data):
    log = logger.new("data_processing")

    try:
        validate_data(log.new("data_validation"), data)
    except Exception as e:
        log.exc(e).error("Data validation failed")

    log.info("Data processed successfully")

def validate_data(log, data):
    log = log.ctx(key=data["key"])

    # Validation happens

    log.info("Data validation successful")

process_data({"key": "value"})

Produces the following output

quickstart example output

Configuration

Global Configuration

import ctxlog
from ctxlog import LogLevel, ConsoleHandler, FileHandler, FileRotation

# Configure with default console handler
ctxlog.configure(
    level=LogLevel.INFO,
    timefmt="iso",  # or "%Y-%m-%d %H:%M:%S"
    utc=True,
)

# Configure with custom handlers
ctxlog.configure(
    level=LogLevel.INFO,
    handlers=[
        ConsoleHandler(
            level=LogLevel.INFO,
            serialize=False,  # Human-readable format
            color=True,
            use_stderr=False,
        ),
        FileHandler(
            level=LogLevel.DEBUG,  # More verbose in file
            serialize=True,  # JSON format
            file_path="./app.log",
            rotation=FileRotation(
                size="20MB",  # Rotate when file reaches 20MB
                keep=5,  # Keep 5 rotated files
                compression="gzip",  # Compress old files
            ),
        ),
    ],
)

Log Levels

ctxlog supports the standard log levels:

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

Advanced Usage

Contextual Logging

def process_payment(payment):
    log = logger.new(event="payment_process").ctx(payment_id=payment.id)
    try:
        transaction_id = charge_payment(payment)
        log.ctx(transaction_id=transaction_id).info("Payment processed")
    except Exception as e:
        log.exc(e).error("Payment failed")

Log Chaining

def process_order(order):
    log = logger.new(event="order_process").ctx(order_id=order.id)
    validate_order(log.new("validation"), order)
    log.info("Order processed")

def validate_order(log, order):
    log = log.ctx(order_id=order.id)

    # Perform validation

    log.info("Order validated")

License

MIT License

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Documentation

The documentation is built using Sphinx and hosted on ReadTheDocs. To build the documentation locally:

# Install development dependencies with documentation extras
poetry install --with docs

# Build the documentation
cd docs
poetry run make html
cd ..

The built documentation will be available in the docs/build/html directory.

Metadata

Release files for ctxlog 1.0.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 ctxlog 1.0.0
File Size Uploaded Provenance Actions
ctxlog-1.0.0.tar.gz 15.2 kB With provenance Details for ctxlog-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ctxlog 1.0.0
File Interpreter ABI Platform Actions
ctxlog-1.0.0-py3-none-any.whl Python 3 none any Details for ctxlog-1.0.0-py3-none-any.whl

Total release size: 30.8 kB

Release files / ctxlog-1.0.0.tar.gz

Download URL ctxlog-1.0.0.tar.gz
Size 15.2 kB
Tags Source
SHA-256 checksum
How to use checksums
c5b0d94d16a6c818c8d4455f60844381df40150a9417e1b2c55b4a46ce9baf89
BLAKE2b-256 checksum
How to use checksums
7a1cde66ad61fece2867651d6d9c287f46455bcb292b9ab8b85d0681d1cb2c3c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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 May 10, 2025.

Transparency log

Release files / ctxlog-1.0.0-py3-none-any.whl

Download URL ctxlog-1.0.0-py3-none-any.whl
Size 15.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
03e5118f6955928e839b6658a1bd951739b1ad152473255f11fe7d3016f9ad92
BLAKE2b-256 checksum
How to use checksums
8a908f8d71ea81bdd8de32e237c84cfcaeb9224ddf8e725cd07c7e7b73828cac
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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 May 10, 2025.

Transparency log

Security for ctxlog 1.0.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

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for ctxlog-1.0.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 May 10, 2025.

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.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files Full provenance

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