function_logging_transformer

Function Logging Transformer Module.

This module provides a LibCST transformer that automatically adds logging statements to functions in Python code. It can be used to instrument code for debugging, performance monitoring, or audit trail generation without manually modifying every function.

The transformer injects a print statement at the beginning of each function body that logs the function name when it is executed, making it easy to trace function calls during program execution.

Examples

>>> from haive.tools.toolkits.dev.python.cst_toolkit.transformers.function_logging_transformer import add_logging
>>> add_logging("path/to/your_script.py")
# This will modify the file, adding logging to all functions

Classes

FunctionLoggingTransformer

Adds logging to function definitions.

Functions

add_logging(→ None)

Inject logging into functions in a Python file.

Module Contents

class function_logging_transformer.FunctionLoggingTransformer(log_format: str = 'Executing {name}', exclude_methods: list[str] | None = None)

Bases: libcst.CSTTransformer

Adds logging to function definitions.

This transformer visits each function definition in the code and adds a print statement at the beginning of the function body that logs the function name when it is executed.

log_format

Format string for the log message, with {name} as placeholder.

exclude_methods

List of method names to exclude from logging.

leave_FunctionDef(original_node: libcst.FunctionDef, updated_node: libcst.FunctionDef) libcst.FunctionDef

Inject logging at the start of every function.

This method is called by the CST visitor when it leaves a function definition. It adds a print statement at the beginning of the function body.

Parameters:
  • original_node – The original function definition node from the CST.

  • updated_node – The potentially modified function definition node.

Returns:

A modified function definition with logging injected.

exclude_methods = []
log_format = 'Executing {name}'
function_logging_transformer.add_logging(filepath: str, log_format: str = 'Executing {name}', exclude_methods: list[str] | None = None) None

Inject logging into functions in a Python file.

This function parses a Python file, adds logging statements to the beginning of each function definition, and writes the modified code back to the file.

Parameters:
  • filepath – Path to the Python file to modify.

  • log_format – Format string for the log message, with {name} as placeholder.

  • exclude_methods – List of method names to exclude from logging.

Raises: