🔍 Code Extractor

function log_controller_action

Maturity: 47

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.

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

Purpose

This decorator is designed to wrap controller functions to provide automatic logging of actions. It distinguishes between routine actions (logged at DEBUG level) and non-routine actions (logged at INFO level) to reduce log spam. It also provides error handling by catching exceptions, logging them with context about which action failed, and re-raising them for proper error propagation.

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):
            # Only log non-routine actions to reduce spam
            routine_actions = {
                'get_document', 'get_documents', 'search_documents',
                'get_user_training_dashboard', 'get_training_overview',
                'get_system_stats', 'get_users', 'get_all_documents'
            }
            
            if action_name not in routine_actions:
                logger.info(f"Controller action: {action_name}")
            else:
                logger.debug(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 performed. This name is used in log messages and compared against a predefined set of routine actions to determine the appropriate log level. Examples include 'get_document', 'create_user', 'delete_document', etc.

Return Value

Returns a decorator function that wraps the target function. The decorator itself returns a wrapper function that executes the original function while adding logging behavior. The wrapper preserves the original function's return value and passes it through unchanged.

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.DEBUG)

def log_controller_action(action_name: str):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            routine_actions = {
                'get_document', 'get_documents', 'search_documents',
                'get_user_training_dashboard', 'get_training_overview',
                'get_system_stats', 'get_users', 'get_all_documents'
            }
            
            if action_name not in routine_actions:
                logger.info(f"Controller action: {action_name}")
            else:
                logger.debug(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

# Usage example
@log_controller_action('create_user')
def create_user(username: str, email: str):
    # This will log at INFO level since 'create_user' is not routine
    return {'username': username, 'email': email}

@log_controller_action('get_document')
def get_document(doc_id: int):
    # This will log at DEBUG level since 'get_document' is routine
    return {'id': doc_id, 'title': 'Sample Document'}

# Call the decorated functions
user = create_user('john_doe', 'john@example.com')
doc = get_document(123)

Best Practices

  • Ensure a logger instance named 'logger' is defined in the module scope before using this decorator
  • The decorator should be applied to controller functions that represent distinct actions in your application
  • Update the 'routine_actions' set if you need to add or remove actions that should be logged at DEBUG level
  • This decorator re-raises exceptions after logging them, so ensure proper exception handling exists at higher levels
  • Use descriptive action_name values that clearly identify what operation is being performed
  • Consider the performance impact of logging in high-frequency operations; routine actions are already optimized to use DEBUG level
  • The decorator preserves function metadata using @wraps, making it safe to use with introspection tools

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function async_action 50.5% 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_debug 48.0% similar

    A logging utility function that writes debug-level messages to a logger named 'EmailForwarder'.

    From: /tf/active/vicechatdev/email-forwarder/src/utils/logger.py
  • function log_user_action 47.6% 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
  • function transaction 47.2% 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 log_performance 46.3% 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
← Back to Browse