Skip to main content

pytracecall: A debugging module with sync and async decorators (CallTracer and aCallTracer) for tracing function calls, and a function (stack) for logging the current call stack

Project description

pytracecall

PyPI version PyPI - Python Version PyPI - License Coverage Status CI/CD Status

Python Call Tracer Module

A debugging module with decorators (CallTracer, aCallTracer) and a function (stack) for tracing function calls and logging the call stack.

This module provides simple yet powerful tools to help you understand your code's execution flow without the need for a full step-by-step debugger. It is designed to integrate seamlessly with Python's standard logging module.


Features

  • Synchronous and Asynchronous Tracing: Decorators for both standard (def) and asynchronous (async def) functions.
  • Concurrency Safe: The async tracer (aCallTracer) uses contextvars to safely trace concurrent tasks without mixing up logs.
  • Data Flow Visibility: Logs function arguments and return values.
  • Recursion Visualization: Automatically indents log messages to clearly show recursion depth, even in concurrent contexts.
  • Stack Inspection: Use the stack() function to log the current call stack at any point in your code.
  • Logging Integration: Works with the standard logging module.

Installation

You can install the package from the Python Package Index (PyPI) using pip.

pip install pytracecall

To ensure you have the latest version, you can use the --upgrade flag:

pip install --upgrade pytracecall

Synchronous Usage

First, ensure you configure Python's logging module to see the output.

Basic Configuration

import logging

# Configure logging to display DEBUG level messages
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%H:%M:%S'
)

Basic Tracing

Use the CallTracer instance as a decorator to trace a synchronous function.

from calltracer import CallTracer

trace = CallTracer()

@trace
def add(x, y):
    return x + y

add(10, 5)

Output:

21:15:10 - DEBUG - --> Calling add(10, 5)
21:15:10 - DEBUG - <-- Exiting add, returned: 15

Asynchronous Usage

The aCallTracer decorator is designed specifically for async def functions and is safe for concurrent execution.

Async Example

import asyncio
import logging
from calltracer import aCallTracer, stack

# Basic logging configuration (can be done once)
logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    datefmt="%H:%M:%S",
)

# Create an instance of the ASYNCHRONOUS tracer
async_trace = aCallTracer(level=logging.DEBUG)

class AsyncDataFetcher:
    @async_trace
    async def process_item(self, item_id: str, delay: float):
        await asyncio.sleep(delay)
        return f"Processed {item_id}"

async def main():
    fetcher = AsyncDataFetcher()
    print("\n--- Running two tasks concurrently to show task-safety ---")
    results = await asyncio.gather(
        fetcher.process_item(item_id="A", delay=0.2),
        fetcher.process_item(item_id="B", delay=0.1),
    )
    logging.info("Concurrent results: %s", results)

if __name__ == "__main__":
    asyncio.run(main())

Example Output (Async)

Note how the logs from Task A and B are interleaved, but the indentation remains correct for each independent task.

--- Running two tasks concurrently to show task-safety ---
22:01:05 - calltracer.async_tracer - DEBUG - --> Calling AsyncDataFetcher.process_item(<...>, item_id='A', delay=0.2)
22:01:05 - calltracer.async_tracer - DEBUG - --> Calling AsyncDataFetcher.process_item(<...>, item_id='B', delay=0.1)
22:01:05 - calltracer.async_tracer - DEBUG - <-- Exiting AsyncDataFetcher.process_item, returned: 'Processed B'
22:01:05 - calltracer.async_tracer - DEBUG - <-- Exiting AsyncDataFetcher.process_item, returned: 'Processed A'
22:01:05 - root - INFO - Concurrent results: ['Processed A', 'Processed B']

API Reference

CallTracer Class (Synchronous)

A factory for creating decorators that trace synchronous (def) function/method calls.

Initialization

from calltracer import CallTracer
trace = CallTracer(level=logging.INFO)

aCallTracer Class (Asynchronous)

A factory for creating decorators that trace asynchronous (async def) function/method calls. This tracer is task-safe for concurrent code using contextvars.

Initialization

from calltracer import aCallTracer
async_trace = aCallTracer(level=logging.INFO)

Parameters for both classes:

  • level (int, optional): The logging level for trace messages. Defaults to logging.DEBUG.
  • logger (logging.Logger, optional): The logger instance to use. Defaults to the internal module logger.

stack() Function

Logs the current call stack to the specified logger. This function works in both synchronous and asynchronous code.

Signature

stack(level=logging.DEBUG, logger=None, limit=None, start=0)
  • level (int, optional): The logging level for the message. Defaults to logging.DEBUG.
  • logger (logging.Logger, optional): The logger instance to use. Defaults to the internal module logger.
  • limit (int, optional): The maximum number of frames to display. Defaults to None (all frames).
  • start (int, optional): The offset of the first frame to display. Defaults to 0.

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

pytracecall-2.0.0.tar.gz (10.7 kB view details)

Uploaded Source

Built Distribution

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

pytracecall-2.0.0-py3-none-any.whl (11.4 kB view details)

Uploaded Python 3

File details

Details for the file pytracecall-2.0.0.tar.gz.

File metadata

  • Download URL: pytracecall-2.0.0.tar.gz
  • Upload date:
  • Size: 10.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.10

File hashes

Hashes for pytracecall-2.0.0.tar.gz
Algorithm Hash digest
SHA256 ad90f59aa2ff4f32b82141aac9ca8d202b2255c2a7f9fee4ce173a8c7a0589b4
MD5 35fc497947ab34b4fa7e737398666a73
BLAKE2b-256 a18c27198c1f266718df428ca08ce28d3d0d7e8650c96a058c1ca152ccb3a720

See more details on using hashes here.

File details

Details for the file pytracecall-2.0.0-py3-none-any.whl.

File metadata

  • Download URL: pytracecall-2.0.0-py3-none-any.whl
  • Upload date:
  • Size: 11.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.10

File hashes

Hashes for pytracecall-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 22377ca8c8438cd2f3dd4be9b062d3c2b378d1e76aa1c563ba9b4656616d8801
MD5 1beb4c5f039bddf5e7e2beed031127c2
BLAKE2b-256 d1b5aabf558ce23917ed0d36e741f7f243c56a0ebb9ad0a87618fba35698b542

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