1from functools import wraps
2
3def logit(func):
4 @wraps(func)
5 def with_logging(*args, **kwargs):
6 print(func.__name__ + " was called")
7 return func(*args, **kwargs)
8 return with_logging
9
10@logit
11def addition_func(x):
12 """Do some math."""
13 return x + x
14
15
16result = addition_func(4)
17# Output: addition_func was called
18
1from functools import wraps
2
3def logit(logfile='out.log'):
4 def logging_decorator(func):
5 @wraps(func)
6 def wrapped_function(*args, **kwargs):
7 log_string = func.__name__ + " was called"
8 print(log_string)
9 # Open the logfile and append
10 with open(logfile, 'a') as opened_file:
11 # Now we log to the specified logfile
12 opened_file.write(log_string + '\n')
13 return func(*args, **kwargs)
14 return wrapped_function
15 return logging_decorator
16
17@logit()
18def myfunc1():
19 pass
20
21myfunc1()
22# Output: myfunc1 was called
23# A file called out.log now exists, with the above string
24
25@logit(logfile='func2.log')
26def myfunc2():
27 pass
28
29myfunc2()
30# Output: myfunc2 was called
31# A file called func2.log now exists, with the above string
32