🔍 Code Extractor

function log_controller_action_v1

Maturity: 47

A decorator factory that wraps controller functions to log their execution and handle exceptions with structured logging.

File:
/tf/active/vicechatdev/CDocs single class/controllers/__init__.py
Lines:
139 - 157
Complexity:
simple

Purpose

This decorator is designed to provide consistent logging for controller actions in a web application or service layer. It logs the start of each action, captures and logs any exceptions that occur during execution, and re-raises them for proper error handling upstream. This is particularly useful for debugging, monitoring, and auditing controller-level operations in applications following MVC or similar architectural patterns.

Source Code

def log_controller_action(action_name: str):
    """
    Decorator to log controller actions.
    
    Args:
        action_name: Name of action being performed
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            logger.info(f"Controller action: {action_name}")
            try:
                result = func(*args, **kwargs)
                return result
            except Exception as e:
                logger.error(f"Error in controller action {action_name}: {e}")
                raise
        return wrapper
    return decorator

Parameters

Name Type Default Kind
action_name str - positional_or_keyword

Parameter Details

action_name: A string identifier for the controller action being decorated. This name appears in log messages to identify which action is being executed or has encountered an error. Should be descriptive and unique to help with log analysis and debugging.

Return Value

Returns a decorator function that wraps the target function. The wrapper function executes the original function, logs its execution, handles exceptions, and returns the original function's result unchanged if successful. If an exception occurs, it logs the error and re-raises the exception.

Dependencies

  • logging
  • functools

Required Imports

import logging
from functools import wraps

Usage Example

import logging
from functools import wraps

# Setup logger
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

# Define the decorator
def log_controller_action(action_name: str):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            logger.info(f"Controller action: {action_name}")
            try:
                result = func(*args, **kwargs)
                return result
            except Exception as e:
                logger.error(f"Error in controller action {action_name}: {e}")
                raise
        return wrapper
    return decorator

# Use the decorator
@log_controller_action("create_user")
def create_user(username: str, email: str):
    print(f"Creating user: {username}")
    return {"username": username, "email": email}

# Call the decorated function
result = create_user("john_doe", "john@example.com")
print(result)

Best Practices

  • Ensure a logger instance is properly configured before using this decorator
  • Use descriptive action_name values that clearly identify the controller action for easier log analysis
  • This decorator re-raises exceptions, so ensure proper exception handling exists at higher levels of your application
  • Consider using this decorator consistently across all controller methods for uniform logging
  • The decorator preserves the original function's metadata using @wraps, making it suitable for use with other decorators
  • Be aware that this logs at INFO level for normal execution and ERROR level for exceptions - configure your logging handlers accordingly
  • For production environments, ensure sensitive data is not included in action_name or function arguments that might be logged

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function log_controller_action 90.3% similar

    A decorator factory that logs controller actions with different log levels based on whether the action is routine or non-routine, and handles exceptions during execution.

    From: /tf/active/vicechatdev/CDocs/controllers/__init__.py
  • function transaction 50.9% similar

    A decorator function that wraps another function to provide database transaction management capabilities, currently implemented as a placeholder for future transaction handling.

    From: /tf/active/vicechatdev/CDocs/controllers/__init__.py
  • function async_action 49.4% similar

    A decorator function that marks another function as asynchronous by adding an 'is_async' attribute, while preserving the original function's metadata.

    From: /tf/active/vicechatdev/CDocs/controllers/__init__.py
  • function log_performance 46.4% similar

    A context manager decorator that logs the performance metrics of an operation by wrapping it with a PerformanceLogger instance.

    From: /tf/active/vicechatdev/contract_validity_analyzer/utils/logging_utils.py
  • function log_user_action 46.0% similar

    Creates an audit event node in a graph database to log user actions, connecting it to both an audit trail and the user who performed the action.

    From: /tf/active/vicechatdev/CDocs/utils/audit_trail.py
← Back to Browse