Skip to main content

pytracecall: A debugging module with a decorator (CallTracer) for tracing function calls and a function (stack) for logging the current call stack

Project description

calltracer

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

Python Call Tracer Module

A debugging module with a decorator (CallTracer) for tracing function calls and a function (stack) for 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

  • Function Call Tracing: Use the @trace decorator to automatically log when a function is entered and exited.
  • Data Flow Visibility: Logs function arguments and return values to see how data flows through your application.
  • Recursion Visualization: Automatically indents log messages to clearly show recursion depth.
  • 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, allowing for flexible configuration of output and levels.

Installation

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

pip install calltracer

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

pip install --upgrade calltracer

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 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

API Reference

CallTracer Class

A factory for creating decorators that trace function/method calls. This class, when instantiated, creates a decorator that can be applied to any function or method to log its entry, exit, arguments, and return value.

Initialization

from calltracer import CallTracer
import logging

# Create a tracer that logs at the INFO level
trace_info = CallTracer(level=logging.INFO)
  • level (int, optional): The logging level to use 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 creates a "snapshot" of how the code reached a certain point, which is useful for point-in-time debugging.

Signature

stack(level=logging.DEBUG, logger=tracer_logger, 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.

Advanced Example

This example demonstrates using both the @trace decorator and the stack() function to debug a recursive function.

import logging
from calltracer import CallTracer, stack

# Basic logging configuration
logging.basicConfig(level=logging.DEBUG, format='%(levelname)s - %(message)s')

# Create a tracer instance
trace = CallTracer()

class AdvancedCalculator:
    @trace
    def factorial(self, n):
        """Calculates factorial and demonstrates stack tracing."""
        # Use stack() for point-in-time analysis when n hits 2
        if n == 2:
            logging.info("--- Dumping stack, because n == 2 ---")
            # Call stack() with INFO level to make it stand out
            stack(level=logging.INFO)

        if n < 0:
            raise ValueError("Factorial is not defined for negative numbers")
        if n == 0:
            return 1
        else:
            return n * self.factorial(n - 1)

# Run the code
calc = AdvancedCalculator()
logging.info("--- Starting recursive call with stack dump ---")
calc.factorial(4)

Example Output

The output clearly shows the trace of factorial calls, interrupted by the stack dump when n is 2.

INFO - --- Starting recursive call with stack dump ---
DEBUG - --> Calling AdvancedCalculator.factorial(<__main__.AdvancedCalculator object at ...>, 4)
DEBUG -     --> Calling AdvancedCalculator.factorial(<__main__.AdvancedCalculator object at ...>, 3)
DEBUG -         --> Calling AdvancedCalculator.factorial(<__main__.AdvancedCalculator object at ...>, 2)
INFO - --- Dumping stack, because n == 2 ---
INFO - Stack trace at /path/to/main.py:18 in factorial():
INFO -   ↳ Called from: /path/to/main.py:25, in factorial
INFO -   ↳ Called from: /path/to/main.py:25, in factorial
INFO -   ↳ Called from: /path/to/main.py:31, in <module>
DEBUG -             --> Calling AdvancedCalculator.factorial(<__main__.AdvancedCalculator object at ...>, 1)
DEBUG -                 --> Calling AdvancedCalculator.factorial(<__main__.AdvancedCalculator object at ...>, 0)
DEBUG -                 <-- Exiting AdvancedCalculator.factorial, returned: 1
DEBUG -             <-- Exiting AdvancedCalculator.factorial, returned: 1
DEBUG -         <-- Exiting AdvancedCalculator.factorial, returned: 2
DEBUG -     <-- Exiting AdvancedCalculator.factorial, returned: 6
DEBUG - <-- Exiting AdvancedCalculator.factorial, returned: 24

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-1.0.2.tar.gz (7.2 kB view details)

Uploaded Source

Built Distribution

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

pytracecall-1.0.2-py3-none-any.whl (8.4 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for pytracecall-1.0.2.tar.gz
Algorithm Hash digest
SHA256 1c958422e41e620070bd0d88d548ef5e49d85a4d93e5fc7253a7ce3b65aea5e7
MD5 0a0a62004e64470adb21f55b16ff328a
BLAKE2b-256 0cd4ac1fb737311fcbfa3f9dc5976e13a93aaec0ab71a10998ca957c38f6782a

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pytracecall-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 8.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-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 51776a737e83ee55862a41ce2ad4ea664b3b9375cbc32fbcde8675efaf470655
MD5 4fac3fef6039017d6af49e03c73bee25
BLAKE2b-256 9bb627cbdbb5b03a127acab85011175e0091f7e5470ea49f8f591e25a60ce146

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