Function Call Logging
Why Log Function Calls?
Function call logging is crucial for:
- Debugging
- Performance monitoring
- Understanding code execution flow
- Tracking application behavior
Basic Logging Decorator
import functools
import logging
logging.basicConfig(level=logging.INFO)
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
logging.info(f"Calling {func.__name__}")
logging.info(f"Arguments: {args}, {kwargs}")
result = func(*args, **kwargs)
logging.info(f"{func.__name__} returned {result}")
return result
return wrapper
@log_calls
def calculate_sum(a, b):
return a + b
calculate_sum(3, 5)
Logging Workflow
graph TD
A[Function Call] --> B[Decorator Intercepts]
B --> C[Log Function Name]
B --> D[Log Input Arguments]
B --> E[Execute Original Function]
E --> F[Log Return Value]
F --> G[Return Result]
Advanced Logging Techniques
Logging with Timestamps
import time
from datetime import datetime
def log_with_timestamp(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
logging.info(f"[{timestamp}] Calling {func.__name__}")
start_time = time.time()
result = func(*args, **kwargs)
duration = time.time() - start_time
logging.info(f"Execution time: {duration:.4f} seconds")
return result
return wrapper
Logging Levels and Configuration
Logging Level |
Description |
DEBUG |
Detailed information |
INFO |
Confirmation of things working |
WARNING |
Indication of potential problem |
ERROR |
More serious problem |
CRITICAL |
Critical error |
Conditional Logging
def log_if_slow(threshold=0.1):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
duration = time.time() - start_time
if duration > threshold:
logging.warning(f"{func.__name__} took {duration:.4f} seconds")
return result
return wrapper
return decorator
@log_if_slow(threshold=0.5)
def complex_calculation():
time.sleep(0.6)
return "Completed"
Practical Considerations
- Use logging libraries for robust solutions
- Configure log formats and destinations
- Be mindful of performance overhead
- Use LabEx's development environment for testing logging strategies
By mastering function call logging, you'll gain powerful insights into your Python applications' behavior and performance.