37. Decorators for Method Logging

Using decorators to log method calls is a powerful way to dynamically add logging functionality to methods without modifying their core logic. Below are several Python snippets demonstrating how to use decorators for method logging in a reusable and flexible way.


1. Basic Logging Decorator

This decorator logs the function name and arguments whenever the decorated method is called.

import functools

def log_method_call(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with arguments {args} and keyword arguments {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

class MyClass:
    @log_method_call
    def greet(self, name):
        return f"Hello, {name}"

obj = MyClass()
obj.greet("Alice")

2. Logging Method Call with Timestamp

This version of the decorator includes the timestamp of when the method is called.


3. Logging Method Call with Exception Handling

In case of an exception, the decorator logs the error message.


4. Logging Method Call with Return Value Modification

This decorator allows modifying the return value before it is returned.


5. Logging Method Call with Function Arguments and Method Name

This decorator logs method calls along with the method name and argument values, showing both positional and keyword arguments.


6. Logging Method Call with Performance Measurement

This decorator logs the execution time of the method.


7. Logging Method Call with Caller Information

This decorator logs the name of the caller method as well.


8. Logging Method Call with Indentation for Nested Calls

This decorator allows you to add indentation for nested method calls to make logs easier to follow.


9. Logging Method Call for Class Methods

This decorator works for both instance methods and class methods.


10. Logging Method Call with Custom Logging Function

This version allows the user to define a custom logging function.


These snippets demonstrate different ways to log method calls, with various customizations such as timestamp logging, performance measurement, exception handling, return value modification, and support for both class methods and instance methods. You can choose the one that fits your needs or further enhance them to suit your specific use case.

Last updated