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.
  • trace_chain (bool, optional): If True, accumulates and logs the call chain. Default to False.
  • 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-3.0.1.tar.gz (11.4 kB view details)

Uploaded Source

Built Distribution

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

pytracecall-3.0.1-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for pytracecall-3.0.1.tar.gz
Algorithm Hash digest
SHA256 d4205e604e1f98b84731c321894814a68e32e4a500745b75383f77e785dd46e8
MD5 7251193acad05897aa76e11cb9f09b7f
BLAKE2b-256 c3351004d052e6adccb1d1d272455a001d931ca45cb572a114a933958efda283

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for pytracecall-3.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 1a85d1814750e87360650d7446458bd8588443592f5026d739f584d0d5840072
MD5 f13a9bf5cb5cd9e59ef41ebe69f194f2
BLAKE2b-256 e5db400fb9d46e3f71ea257203cca824e5b7fe1a2a31a049b37e4a69ea07e9c0

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