Python Decorators: Custom Logging for Function Calls
-
wrote on 7 Sept 2023, 05:38 last edited by
I'm working on a Python project where I have multiple functions, and I want to log each function call along with its arguments and return value for debugging purposes. I've heard that decorators can help achieve this. Could someone guide me on how to create a custom decorator for logging function calls?
Here's what I have in mind:
def log_function_call(func): def wrapper(*args, **kwargs): # Log function call, arguments, and return value result = func(*args, **kwargs) # Log the result return result return wrapper @log_function_call def add(a, b): return a + b @log_function_call def subtract(a, b): return a - b # Example function calls result1 = add(5, 3) result2 = subtract(10, 4)
I'd like to log the function calls and their results in a clean and organized manner. How can I modify the log_function_call decorator to achieve this? Additionally, what's the best practice for configuring the logger in Python to capture these logs effectively? Any code examples or recommendations would be greatly appreciated. Thank you!
-
I'm working on a Python project where I have multiple functions, and I want to log each function call along with its arguments and return value for debugging purposes. I've heard that decorators can help achieve this. Could someone guide me on how to create a custom decorator for logging function calls?
Here's what I have in mind:
def log_function_call(func): def wrapper(*args, **kwargs): # Log function call, arguments, and return value result = func(*args, **kwargs) # Log the result return result return wrapper @log_function_call def add(a, b): return a + b @log_function_call def subtract(a, b): return a - b # Example function calls result1 = add(5, 3) result2 = subtract(10, 4)
I'd like to log the function calls and their results in a clean and organized manner. How can I modify the log_function_call decorator to achieve this? Additionally, what's the best practice for configuring the logger in Python to capture these logs effectively? Any code examples or recommendations would be greatly appreciated. Thank you!
wrote on 7 Sept 2023, 06:45 last edited by@Sachin-Bhatt Since this is a Qt forum you may get better answers by search for/going to a Python forum, for logging.
-
Hi,
This article contains exactly what you are looking for.
1/3