I am currently using the following code to log messages based on their log_level in customized fashion.
What i am struggling is how to update or change the function name in the common LOG_MSG
function.
Currently it logs all messages with function name as LOG_MSG
, I want to replace it with the actual function names FunctionNum1
or FunctionNum2
.
import logging
import inspect
INFO = "INFO"
DEBUG = "DEBUG"
WARN = "WARNING"
ERROR = "ERROR"
def LOG_MSG(level, msg_str, msg_val,tee_output):
if msg_val == None:
msg_val = ""
if(level == INFO):
logging.info ( msg_str + msg_val )
elif(level == DEBUG):
logging.debug ( msg_str + msg_val )
elif(level == WARN):
logging.warn ( msg_str + msg_val )
elif(level == ERROR):
logging.error ( msg_str + msg_val )
if(tee_output):
print ( msg_str + msg_val )
date_strftime_format = "%d-%b-%y %H:%M:%S"
message_format='%(asctime)s %(levelname)s %(module)s - %(funcName)s: %(message)s'
logging.basicConfig(filename = 'log_messages.log', format = message_format, datefmt = date_strftime_format,level=logging.DEBUG)
def FunctionNum1():
this_function_name = inspect.currentframe().f_code.co_name
print this_function_name
LOG_MSG(INFO,"This is an Info Msg=","Any Value",1)
LOG_MSG(WARN,"This is a Warning Msg",None,0)
LOG_MSG(INFO,"This is an Info Msg",None,1)
def FunctionNum2():
this_function_name = inspect.currentframe().f_code.co_name
print this_function_name
somevalue = "someValue"
LOG_MSG(DEBUG,"This is a Debug Msg = ",somevalue,1)
LOG_MSG(INFO,"This is an Info Msg=","12",1)
LOG_MSG(ERROR,"This is a Error Msg",None,1)
if __name__ == "__main__":
FunctionNum1()
FunctionNum2()
OUTPUT:
20-Apr-21 15:55:58 INFO log_utility - LOG_MSG: This is an Info Msg=Any Value
20-Apr-21 15:55:58 WARNING log_utility - LOG_MSG: This is a Warning Msg
20-Apr-21 15:55:58 INFO log_utility - LOG_MSG: This is an Info Msg
20-Apr-21 15:55:58 DEBUG log_utility - LOG_MSG: This is a Debug Msg= someValue
20-Apr-21 15:55:58 INFO log_utility - LOG_MSG: This is an Info Msg=12
20-Apr-21 15:55:58 ERROR log_utility - LOG_MSG: This is a Error Msg