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-3.0.0.tar.gz (11.3 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.0-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pytracecall-3.0.0.tar.gz
  • Upload date:
  • Size: 11.3 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.0.tar.gz
Algorithm Hash digest
SHA256 b37bc9954d36a048f7682996a1708be463d29b2e1352693a6d085b0da51633ca
MD5 5f268b88742b231424a66dbb243aa6fb
BLAKE2b-256 3d9b0f8a0ea2ecd81c812b466959fa888b35d4483d63eb669faa120686b58f60

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pytracecall-3.0.0-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.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c80abef51a46b9cfee8327e998cf87d3ac1ac0bf0fb63bb3f6af8d2e4a7533d0
MD5 7e36250f72d9bcce08e6a51aea21706d
BLAKE2b-256 e123e77f6dbbcdece6859faeed8e97d15bc293524b5d29ac8781f6a206ecaf06

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