3

最近我遇到了登录python。

我在 test.py 文件中有以下代码

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
logger.debug("test Message")

现在,有什么方法可以打印Logrecord生成的结果对象,logger.debug("test Message")因为它在文档中说明

每次记录某些内容时,Logger 都会自动创建 LogRecord 实例

https://docs.python.org/3/library/logging.html#logrecord-objects

我检查了保存debug到变量中并打印它

test = logger.debug("test Message")
print(test)

输出是NONE

我的目标是检查/查看logging.debug(test.py)在同一个 test.py 中生成的最终 Logrecord 对象,print()这是为了我自己的理解。

print(LogrecordObject.__dict__)

那么如何获取Logrecord生成的对象logger.debug("test Message")

4

2 回答 2

1

没有回报debug()

# Here is the snippet for the source code
    def debug(self, msg, *args, **kwargs):
        if self.isEnabledFor(DEBUG):
            self._log(DEBUG, msg, args, **kwargs)

如果你想获得 LogRecord 返回,你需要重新定义 a debug(),你可以像这样覆盖:

import logging

DEBUG_LEVELV_NUM = 9 
logging.addLevelName(DEBUG_LEVELV_NUM, "MY_DEBUG")

def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
    sinfo = None
    fn, lno, func = "(unknown file)", 0, "(unknown function)"
    if exc_info:
        if isinstance(exc_info, BaseException):
            exc_info = (type(exc_info), exc_info, exc_info.__traceback__)
        elif not isinstance(exc_info, tuple):
            exc_info = sys.exc_info()
    record = self.makeRecord(self.name, level, fn, lno, msg, args,
                             exc_info, func, extra, sinfo)
    self.handle(record)
    return record


def my_debug(self, message, *args, **kws):
    if self.isEnabledFor(DEBUG_LEVELV_NUM):
        # Yes, logger takes its '*args' as 'args'.
        record = self._log(DEBUG_LEVELV_NUM, message, args, **kws)
        return record

logger = logging.getLogger(__name__)
logging.Logger.my_debug = my_debug
logging.Logger._log = _log
logger.setLevel(DEBUG_LEVELV_NUM)
logger.addHandler(logging.StreamHandler())
test = logger.my_debug('test custom debug')
print(test)

参考: 如何将自定义日志级别添加到 Python 的日志记录工具

于 2019-08-12T06:17:15.607 回答
0

您可以创建一个处理程序,而不是将 LogRecord 实例格式化为字符串,只需将其保存在列表中以供稍后查看和检查:

import logging
import sys


# A new handler to store "raw" LogRecords instances
class RecordsListHandler(logging.Handler):
    """
    A handler class which stores LogRecord entries in a list
    """
    def __init__(self, records_list):
        """
        Initiate the handler
        :param records_list: a list to store the LogRecords entries
        """
        self.records_list = records_list
        super().__init__()

    def emit(self, record):
        self.records_list.append(record)


# A list to store the "raw" LogRecord instances
logs_list = []

# Your logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Add the regular stream handler to print logs to the console, if you like
logger.addHandler(logging.StreamHandler(sys.stdout))

# Add the RecordsListHandler to store the log records objects
logger.addHandler(RecordsListHandler(logs_list))


if __name__ == '__main__':

    logger.debug("test Message")
    print(logs_list)

输出:

test Message
[<LogRecord: __main__, 10, C:/Automation/Exercises/222.py, 36, "test Message">]
于 2020-06-07T06:44:28.067 回答