更新日志中的函数名称

Update function name in logging

我目前正在使用以下代码以自定义方式根据 log_level 记录消息。
我正在努力的是如何更新或更改公共 LOG_MSG 函数中的函数名称。

目前它记录了函数名称为 LOG_MSG 的所有消息,我想用实际函数名称 FunctionNum1FunctionNum2.

替换它
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()

输出:

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

您可以通过更改记录器的信息(在导入记录模块之后)来实现:

logger = logging.getLogger() # load logging manager
oldMakeRecord = logger.makeRecord

def customMakeRecord(*args, **kwargs):
    # get usual record information
    rv = oldMakeRecord(*args, **kwargs)

    # change function name with what you want
    rv.funcName = "abc"

    return rv

# replace original manager with new one
logger.makeRecord = customMakeRecord

哪些输出(在log_messages.log):

20-Apr-21 14:08:39 INFO main - abc: This is an Info Msg=Any Value
20-Apr-21 14:08:39 WARNING main - abc: This is a Warning Msg
20-Apr-21 14:08:39 INFO main - abc: This is an Info Msg
20-Apr-21 14:08:39 DEBUG main - abc: This is a Debug Msg = someValue
20-Apr-21 14:08:39 INFO main - abc: This is an Info Msg=12
20-Apr-21 14:08:39 ERROR main - abc: This is a Error Msg

在这里和那里进行一些调整,我相信您将能够自动找到函数名称(How to use inspect to get the caller's info from callee in Python? 可能是一个很好的信息来源)。

虽然可能有更好的方法来做到这一点,但我不太使用日志记录和检查模块。

编辑:更完整的解决方案

我们可以创建一个函数,用给定的函数名称更新记录器;每次我们尝试记录一些东西时都使用它。当我们这样做时,我们可以使用 inspect 模块找到正确的函数名称作为参数。

def update_logger(function_name: str):
    logger = logging.getLogger()
    oldMakeRecord = logger.makeRecord

    def customMakeRecord(*args, **kwargs):
        rv = oldMakeRecord(*args, **kwargs)
        rv.funcName = function_name
        return rv

    logger.makeRecord = customMakeRecord

def LOG_MSG(level, msg_str, msg_val,tee_output):
    # find function name with inspect module
    caller_function_name = inspect.currentframe().f_back.f_code.co_name
    update_logger(function_name=caller_function_name)

    # the rest is the normal behavior of the log_msg function
    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 )

log_messages.log 文件现在包含:

22-Apr-21 13:41:58 INFO logging_format - FunctionNum1: This is an Info Msg=Any Value
22-Apr-21 13:41:58 WARNING logging_format - FunctionNum1: This is a Warning Msg
22-Apr-21 13:41:58 INFO logging_format - FunctionNum1: This is an Info Msg
22-Apr-21 13:41:58 DEBUG logging_format - FunctionNum2: This is a Debug Msg = someValue
22-Apr-21 13:41:58 INFO logging_format - FunctionNum2: This is an Info Msg=12
22-Apr-21 13:41:58 ERROR logging_format - FunctionNum2: This is a Error Msg