Implementing a Python decorator for function logging
Python Decorator: Exercise-8 with Solution
Write a Python program that implements a decorator to add logging functionality to a function.
Logging functionality refers to the capability of recording and storing information about program execution. It allows you to capture significant events, messages, and errors that occur during code execution.
Sample Solution:
Python Code:
def add_logging(func):
def wrapper(*args, **kwargs):
# Log the function name and arguments
print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
# Call the original function
result = func(*args, **kwargs)
# Log the return value
print(f"{func.__name__} returned: {result}")
# Return the result
return result
return wrapper
# Example usage
@add_logging
def add_numbers(x, y):
return x + y
# Call the decorated function
result = add_numbers(200, 300)
print("Result:", result)
Sample Output:
Calling add_numbers with args: (200, 300), kwargs: {} add_numbers returned: 500 Result: 500
Explanation:
In the above exercise,
The code defines a decorator called add_logging that adds logging functionality to a function. When a function is decorated with @add_logging, it wraps the original function and performs the following actions:
- Log the function name and arguments before calling the original function.
- Call the original function.
- Log the return value after the function execution.
- Return the result.
In the example usage, the add_numbers function is decorated with @add_logging. When the decorated function is called, the decorator logs the function name, arguments, and return value.
Flowchart:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Implementing a Python decorator for function rate limits.
Next: Implementing a Python decorator for exception handling with a default response.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/decorator/python-decorator-exercise-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics