Logging Decorator in Python
Logging is very important in software development. Tracking events, debugging & application analysis is performed using Logging.
Python comes with standard module logging
which implements logging system for applications and libraries.
In this Python program, we design logger decorator without using logging module. This decorator then can be used to decorate function which logs some message. For now message is printed in standard output but you can modify to store it into file or database.
Python Source Code: Logger Decorator
# Logger decorator
def logger(fn):
from datetime import datetime, timezone
def inner(*args, **kwargs):
called_at = datetime.now(timezone.utc)
to_execute = fn(*args, **kwargs)
print('{0} executed. Logged at {1}'.format(fn.__name__, called_at))
return to_execute
return inner
@logger
def function_1():
pass
@logger
def function_2():
pass
@logger
def function_3():
pass
@logger
def function_4():
pass
function_1()
function_4()
function_2()
function_3()
function_1()
function_4()
Output
function_1 executed. Logged at 2020-05-26 03:23:08.714904+00:00 function_4 executed. Logged at 2020-05-26 03:23:08.714904+00:00 function_2 executed. Logged at 2020-05-26 03:23:08.715902+00:00 function_3 executed. Logged at 2020-05-26 03:23:08.715902+00:00 function_1 executed. Logged at 2020-05-26 03:23:08.715902+00:00 function_4 executed. Logged at 2020-05-26 03:23:08.715902+00:00