Decorators in Python are powerful tools that allow you to add functionality to existing functions or classes without modifying their source code. When combined with logging, they become a clean way to track function calls, arguments, and execution times.

📌 Why Use Decorators for Logging?

  • Reusability: Apply consistent logging behavior across multiple functions
  • Maintainability: Centralize logging logic instead of duplicating it
  • Flexibility: Easily enable/disable logging for specific functions

🧠 Basic Structure of a Logging Decorator

import logging
from functools import wraps

def log_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        logging.info(f"Calling function: {func.__name__}")
        result = func(*args, **kwargs)
        logging.info(f"Function {func.__name__} completed")
        return result
    return wrapper

📝 Example Usage

@log_decorator
def add(a, b):
    return a + b

add(3, 5)

📈 Advanced Features

  • Parameter Logging:

    def log_params(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            logging.info(f"Arguments: {args}, {kwargs}")
            return func(*args, **kwargs)
        return wrapper
    
  • Timing Execution:

    import time
    
    def log_time(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            logging.info(f"Execution time: {time.time() - start:.4f}s")
            return result
        return wrapper
    

🧩 Combining Decorators

@log_params
@log_time
def multiply(a, b):
    return a * b

📚 Recommended Reading

Learn more about decorators in Python or explore advanced logging techniques.

Python_decorator
Logging_decorator