Home > Back-end >  How to define a decorator function which logs information about a function and the arguments passed
How to define a decorator function which logs information about a function and the arguments passed

Time:02-07

I want to define a decorator function which logs information about a function and the arguments passed to it.

Input:

hello world

output should be:

Accessed the function -'greet' with arguments ('hello world!',) {}

I have tried but I am not getting exact output

import sys
import os
import datetime as dt

#Add log function and inner function implementation here
def log(func):
    def inner(msg):
        str_template = "Accessed the function -'{}' with arguments {}".format(func.__name__,msg)
        return str_template
    return inner

    
@log
def greet(msg):
    return msg


'''Check the Tail section for input/output'''
if __name__ == "__main__":
    with open(os.environ['OUTPUT_PATH'], 'w') as fout:
        res_lst = list()
        res_lst.append(greet(str(input())))
        fout.write("{}".format(*res_lst))

I am getting below output

Accessed the function -'greet' with arguments hello world

CodePudding user response:

I suspect something like this is what you want:

def log(func):
    def inner(*args, **kwargs):
        str_template = "Accessed the function -'{}' with arguments {}".format(func.__name__, args, kwargs)
        func(*args, **kwargs)
        return str_template
    return inner

@log
def useless(message):
    print("Message: ", message)
    return message # THIS IS HERE TO SHOW THAT THE RETURN IS OVERRIDEN IN YOUR CODE

hello = useless('Hello!')
print("Return of function useless is: ", hello)

If you don't want to overwrite the function you're decorating, use return func(*args, **kwargs) instead of return str_template. Note that you'll have to print str_template if you're not returning it, otherwise it's not being used...

Output:

Message:  Hello!
Return of function useless is:  Accessed the function -'useless' with arguments ('Hello!',)

CodePudding user response:

Just change the format string to produce the required output:

def log(func):
    def inner(msg):
        str_template = "Accessed the function -'{}' with arguments ('{}',){{}}".format(func.__name__,msg)
        return str_template
    return inner

Output as expected.

  •  Tags:  
  • Related