Python Decorators: Custom Logging for Function Calls (1 Viewer)

bettey12

New member
Local time
Today, 15:03
Joined
Jun 20, 2022
Messages
8
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:
Python:
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)
 

CJ_London

Super Moderator
Staff member
Local time
Today, 10:33
Joined
Feb 19, 2013
Messages
16,612
There may be some python developers on this forum but you are more likely to get an informed response from a python forum
 

Uncle Gizmo

Nifty Access Guy
Staff member
Local time
Today, 10:33
Joined
Jul 9, 2003
Messages
16,282
ChatGPT said:-

Code:
import logging

logging.basicConfig(level=logging.INFO)

def log_function_call(func):
    def wrapper(*args, **kwargs):
        logging.info(f"Calling function {func.__name__} with arguments {args} and keyword arguments {kwargs}")
        result = func(*args, **kwargs)
        logging.info(f"Function {func.__name__} returned {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)
 

Users who are viewing this thread

Top Bottom