function log_controller_action_v1
A decorator factory that wraps controller functions to log their execution and handle exceptions with structured logging.
/tf/active/vicechatdev/CDocs single class/controllers/__init__.py
139 - 157
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
loggingfunctools
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function log_controller_action 90.3% similar
-
function transaction 50.9% similar
-
function async_action 49.4% similar
-
function log_performance 46.4% similar
-
function log_user_action 46.0% similar